Convert date to month year format and pass it in the query - sql

I have a BIRT report where user will be entering the dates in dd-mm-yyyy format however I need to convert dd-mm-yyyy to MON-YYYY format.
I have tried to use VARCHAR_FORMAT(FIELDNAME,'MON-YYYY') however it doesn't work.
select …….
where VARCHAR_FORMAT(fieldname,'MON-YYYY') = '2017-05-15';
User would end the date as
15/05/2017
The value present in the database for this field is 2017-05-15 07:30:00.0

update
Apparently the column is not a string but a datetime which means the conversion is only
to_date(fieldname, 'MON-YYYY')
But if the column is used in a Where clause it shouldn’t be converted at all.
——
Use to_date and to_char to first convert your string to a date and then back to a string with the right format
to_char(to_date(fieldname, 'DD-MM-YYYY'), 'MON-YYYY')

select *
from table (values
timestamp('2017-05-15-07.30.00')
) t(fieldname)
where
fieldname between to_date('15/05/2017', 'DD/MM/YYYY') and to_date('15/05/2017', 'DD/MM/YYYY') + 1 day
--date(fieldname) = to_date('15/05/2017', 'DD/MM/YYYY')
;
You may run it as is.
Both cases work, but to use the 2-nd one efficiently, you must create an index by the date(fieldname) expression (since db2 10.5) or add generated always column to the table with the same expression and index on it.

Related

Oracle's SQL how to convert the date's format

this is my table:
table name EXAMPLE
column name DATE
this is the output for the following query:
SELECT date
FROM example;
1/23/2010
I want to convert the output to:
23-Jan-10
Is it possible?
Thanks
You can use formatting along with TO_CHAR() conversion such as
SELECT TO_CHAR(dt,'DD-Mon-RR')
FROM example
where
DATE is not a good name for a column as being a reserved keyword. So, I've replaced it with dt
If your column is in varchar/text.. then you can first convert to date then back to char
SELECT
TO_CHAR(
to_date('1/23/2010','mm/dd/yyyy'),'DD-Mon-YY'
)
datec FROM dual;
If it is in date format, to_char only will do
SELECT
TO_CHAR(date_column, 'DD-Mon-YY' )
datec FROM dual;
A DATE data type is a binary format that is stored in 7-bytes that has no format and always contains the components: year (stored as century and year-of-century), month, day, hour, minute and second.
Therefore, you cannot change the format of a DATE data type.
If instead, you ask the question:
How can format a DATE to output it as 23-Jan-10?
Then you can convert the DATE to a formatted string using the TO_CHAR function:
SELECT TO_CHAR(your_date_column, 'DD-MON-YY', 'NLS_DATE_LANGUAGE=English')
AS formatted_date
FROM your_table;
Alternatively, if you want the output as a DATE data type then you can use:
SELECT your_date_column
FROM your_table;
and change the user interface (SQL/Plus, SQL Developer, Toad, PLSQLDeveloper, PHP, Java, etc.) you are using to alter how that that user interface displays dates. The solution is going to depend on which user interface you are using but for SQL/Plus and SQL Developer, you can change Oracle's NLS_DATE_FORMAT session parameter:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YY';
Other user interfaces will have different solutions specific to those interfaces.

Oracle SQL - convert a varchar2 into a date

I have a problem with converting a varchar2 fields into a date format.
I got 2 columns with the datatyp varchar2, one is called qtime the other is called ztime. Both fields contain strings in this format (f.e. 152015 -> would be a timestamp 15:20:15).
For reporting reasons I need to convert this fields into a date format, afterwards I want to substract (qtime-ztime) the fields an convert them into the format [hh] (f.e. after the operation 01:20:00 would be -> 01). Is it possible to to this within Oracle SQL 12c? The biggest problem for me right now is that I don't get those Strings converted into a date format.
select TO_DATE(qtime,'MM/DD/YYYY hh24:mi:ss') just gives me
ORA-01861:"literal does not match format string"
select TO_DATE(qtime,'hh24mmss') gives me a wrong Date
01.03.2018
select TO_TIMESTAMP(qtime,'hh24mmss') gives me a wrong Date
01.03.2018 BUT the correct time with f.e. 15:20:15,0000000
Thank you in advance, any help is appreciated
Note: I only have reading rights on the database Oracle 12c, so I need to to this within Statements
"The Database contains another column with the correct date for each time"
The missing piece of the puzzle! Concatenate the two columns to get something which can be converted to an Oracle DATE:
select to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
Once you have done that you can perform arithmetic of the dates e.g.
select id
, zdatetime - qdatetime as time_diff
from ( select id
, to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
)
If you want the number of hours in the difference you can include this expression in the projection of the outer query:
, extract( hour from (zdatetime - qdatetime) day to second) as hrs_ela
First off, if you are trying to convert a varchar2 into a date without specifying neither day nor month, it will default to the first day of the current month:
If you specify a date value without a date, then the default date is the first day of the current month.
You can read up more here
Also in 2nd and 3rd your example, you are using 'hh24mmss' for specifying hour, minute and second components, but do note that correct format for minutes is 'mi' and not 'mm', which is used for months.
So the solution is to concatenate both date and time component when creating the date as the other answer suggested, tho I would recommend using a single date field as it can store the information you need.

To get all the dates in a format dd/mm/yyyy. I have a date field in the format yyyymmdd

In my DB, there is a date field in the format yyyymmdd.
I have to get all the dates in the format dd-mm-yyyy for that particlar date.
ex:
Date
20170130
20170228
20170325
for the above dates, I need the output in the below format with the dates and day of the particular dates
date day
30-01-2017 tuesday
28-02-2017 tuesday
25-03-2017 saturday
If the column is a string, then it can hold invalid date values such as February 31, one way to avoid this is by a small function such as this:
create or replace
function my_to_date( p_str in varchar2 ) return date
is
begin
return to_date( p_str );
exception
when others then
return null;
end;
\\
select to_char(my_to_date('20170231'),'DD-MM-YYYY Day')
from dual
\\
Demo
Try below:
Select to_char(yrdate, 'dd-mm-yyyy'), to_char(yrdate, 'D') from yrtable
It sounds like your dates aren't actually DATE fields but some kind of CHAR field? The best option would be to convert to DATE and then convert back to CHAR:
SELECT TO_CHAR(TO_DATE(mydate, 'YYYYMMDD'), 'DD-MM-YYYY Day')
FROM mytable;
This uses the YYYYMMDD mask to convert your string into a date, then uses the mask DD-MM-YYYY Day to convert it back into a string. Use day if you want the day name in lowercase (as in your OP).
#user2778168 answer will give you the results you want. But why?
Your database does not have dates stored in yyyymmdd format or any other date format for at mater, unless it's defined with a character type definition. Oracle stores all dates in a single internal structure, and with only slight variations timestamps are the same. The format used only tells Oracle how to display the value or to convert a string to a date. Unless a specific format is specified Oracle uses the NLS_DATE_FORMAT for this determination. See here and scan down to "Datetime Format Models" for format specifications.
To see this run the following:
select value
from nls_session_parameters
where parameter = 'NLS_DATE_FORMAT';
Select yrdate default_format
, to_char(yrdate, 'dd-mm-yyyy') specified_format
, dump(yrdate) unformated
from yrtable;
alter session set nls_date_format = 'Month dd,yyyy';
Rerun the above queries.
It seems you hold date column(date1) in character format. Suppose you have a table named days:
SQL> desc days
date1 varchar2(10)
then,
we should convert it into date, and then into char format, with aliases in quotation marks to provide lowercase aliases as you wanted.
perhaps your database's date language is non-english like mine(turkish), then you need to convert it to english.
lastly, it'a appropriate to order the results according to converted date, seen from your output. So we can use the following SQL :
select to_char(to_date(date1,'yyyymmdd'),'dd-mm-yyyy') "date",
to_char(to_date(date1,'yyyymmdd'),'day','nls_date_language=english') "day"
from days
order by to_date(date1,'yyyymmdd');
D e m o

Searching Between Two Dates With A Specific Format

So I have a table where the dates are formatted as such: 15-Jan-13
That would obviously be January 15th, 2013.
The problem is, when I try to search a date range between 01/01/2014 and SYSDATE, it errors out.
Does anyone know the proper way in which I would format this based off of how my dates are stored?
FYI my raw data is stored as: 15-JAN-13 02.23.27.000000000 PM -05:00
I'm converting it as
TRUNC(variable_name)
Given that you are asking about "sysdate" then I would assume you are using Oracle. It would also seem that the the column with the dates are not actual in the date format. Best option would be to change the column to a date type. If for some reason that isn't an option, the next best thing to do is to translate the text to a date as part of your query:
select *
from foo
where to_date(your_column, 'dd-Mon-yy') between to_date('01/01/2014', 'mm/dd/yyyy')
and sysdate
Note that to_date is expecting it's second argument to match the structure of the date specified so '01/01/2014' would match the date format 'mm/dd/yyyy' and your_column (value: '15-Jan-13') would match a different format 'dd-Mon-yy'. Once everything is translated to a date, Oracle can perform appropriate date comparisons.
DISCLAIMER: The translation of your_column to a date using to_date means that if an index is defined on your_column, it won't be used. If this is a large table you can expect sub-optimal performance. One additional reason to change the column data type to a date.

Select Varchar as Date

I want to select a varchar field as a date field
For example a field has this value "30.12.2011 21:15:03"
and when i select this
select DATE from TABLE where DATE = '30.12.2011'
i get no result.
You ask about getting the date part of a timestamp field, but what your question is actually about is filtering on the date of a timestamp field. There is a much simpler method of accomplishing that: you can use the knowledge that all the possible timestamps on a specific date won't have any timestamps for different dates between them.
select DATE
from TABLE
where DATE >= '30.12.2011' and DATE < '31.12.2011'
Your edit explains that you haven't got a timestamp field at all. Nevertheless, a similar approach may still work:
select DATE
from TABLE
where DATE LIKE '30.12.2011 %'
Or the Firebird-specific
select DATE
from TABLE
where DATE starting with '30.12.2011 '
Assuming the field is a date field, use the DATE introducer combined with yyyy-mm-dd (or TIMESTAMP with time as well).
So use:
select datefield from sometable where datefield = DATE '2011-12-30'
Technically you can leave off the introducer, but it is 'correcter' in the light of the SQL standard.
Assuming a TIMESTAMP field, you won't get results unless the timestamp is (always) at 00:00:00.0000 (in which case it should have been a DATE instead).
For the comparison to work, you need to use either BETWEEN, eg:
select timestampfield from sometable
where timestampfield BETWEEN '2011-12-30 00:00:00.0000' AND '2011-12-30 23:59:59.9999'
or truncate the timestamp to a date (this may adversely effect performance if the timestamp is indexed, because then the index can no longer be used), eg:
select timestampfield from sometable
where CAST(timestampfield AS DATE) = '2011-12-30'
If the date is stored in a VARCHAR field (which in itself is a bad idea), there are several solutions, first is to handle it as date manipulation:
select varcharfield from sometable
where CAST(CAST(varcharfield AS TIMESTAMP) AS DATE) = '2011-12-30'
The double cast is required if you have a time-component in VARCHARFIELD as well. This assumes dates in the supported format listed below. If you use BETWEEN as above, you can use a single cast to timestamp)
The other solution (as suggested by hvd) is to treat it purely as string manipulation, for example:
select varcharfield from sometable
where varcharfield STARTING WITH '30.12.2011'
This has its own set of problems if you want to select ranges. Bottomline: use a real TIMESTAMP field!
Note that Firebird supports multiple formats:
yyyy-mm-dd, eg 2014-05-25 (ISO-8601 format, probably best to use as it reduces confusion)
dd.mm.yyyy, eg 25.05.2014
mm/dd/yyyy, eg 05/25/2014
mm-dd-yyyy, eg 05-25-2014
dd mmm yyyy, eg 25 MAY 2014 (+ variations with a -, . or / as separator)
mmm dd yyyy, eg MAY 25 2014 (+ variations with a -, . or / as separator)
select DATE from TABLE where cast(DATE as date) = '30.12.2011'
Date field is a timestamp
Here is the answere to my question:
CAST
(
SUBSTRING
(field FROM 1 FOR 2)
||'.'||
SUBSTRING
(field FROM 4 FOR 2)
||'.'||
SUBSTRING
(field FFROM 7 FOR 4)
AS DATE)
This took me 5 hours to find this out, maybe there should be a "-" instead of "." but it works.