I've got a datetime field in my table which shows dates like this:
2017-01-18 10:20:19.617
I'm using QUOTENAME to output the table with the fields wrapped in quotes so it will be compatible to import into a legacy CSV based app.
SELECT QUOTENAME(P.CreatedOn,'"') as CreatedOn
That changes the output to
"Jan 18 2017 10:20AM"
Ideally I need
"2017-01-18 10:20:19.617"
Is that possible?
This should do the trick. The CONVERT function allows you to explicitly control the format of your date conversion.
declare #d datetime = '20170119 20:21:22'
select QUOTENAME(CONVERT(varchar(23), #d, 121), '"')
Some guidance notes:
The style parameter 121 indicates the date/time must be formatted in the ODBC format which is yyyy-mm-dd HH:MM:ss[.ttt[tttt]][{+|-}offset]. It always includes the fractions of a second at 3 or 7 digits depending on the date type of the value to be converted.
This supports all datatypes combining date & time: datetime, datetime2 (7 digit fraction of a second), smalldatetime, datetimeoffset
date and time datatypes exclude time a date portions from the string respectively.
Refer to the linked page to experiment with other conversion styles. E.g. style 120 is similar, but excludes the optional fractions of a second from the format.
Note that if the the varchar(...) target type is to short to hold the full string, it will be truncated from the right.
QUOTENAME returns nvarchar (258). When you are supplying DATE to the function it does conversion to nvarchar.
If you convert to varchar or nvarchar first (as #CraigYoung suggesting), then this function will not do conversion itself and will not change the string.
In CONVERT you can specify any format you want for your date to be in using list available formats.
Related
I would like to transform a UTC timestamp with 5-6 ms digits into a SQL Server datetime. I do not want to localize or anything, just want to keep UTC but turn it into a datetime
e.g.
declare #utc_timestamp varchar(20) = '2022-10-05T13:12:02.000402Z';
-- Desired datetime format (is this even possible or does this not conform to SQL Server's datetime format?
2022-10-05 13:12:02.000402
Interestingly, this works:
declare #utc_timestamp varchar(20) = '2022-10-05T13:12:22Z';
select cast(#utc_timestamp as datetime)
-- result
2022-10-05 13:12:22.000
So it leads me to believe that SQL Server's datetime can only parse a UTC timestamp if it doesn't have too many ms digits.
You can use datetime2 for this, it has a higher precision.
select cast('2022-10-05T13:12:02.000402Z' as datetime2)
#Vvdl already wrote an answer explaining how to solve this. I want to supplement that by providing references to the relevant parts of the documentation.
Allowed formats for datetime are documented here: Supported string literal formats for datetime. The section on ISO 8601 lists the following format:
YYYY-MM-DDThh:mm:ss[.mmm]
datetime2, on the other hand, supports more decimal places: Supported string literal formats for datetime2
YYYY-MM-DDThh:mm:ss[.nnnnnnn]
In the examples, the documentation further explains that "...[t]he time zone is truncated...", which explains why the trailing Z is allowed, even though it does not match the format described above.
I'm using SQL Server 2014. I have a date stored as varchar(MAX) in the format of:
2019-02-18
However, I want it in the British format dd/mm/yyyy (103).
This is my SQL:
SELECT CONVERT(DATE, DateField, 103) AS "JobStartDate"
FROM tblTest
However, I keep getting this error:
Conversion failed when converting date and/or time from character string.
What am I missing?
Update: The date is initially stored as varchar max as it is coming from a 3rd party system. I have no control over this and I completly understand this is the wrong format, but this is what I have been given.
I have a date stored as varchar(MAX)
There's your problem right there.
Not only you are using the wrong data type to store dates, you are also using max which is a known performance killer.
The solution to the problem is to alter the table and store dates in a Date data type - but first, you must look up all the objects that depends on that column and make sure they will not break or change them as well.
Assuming this can't be done, or as a temporary workaround, you must first convert the data you have to Date, and then convert it back to a string representation of that date using the 103 style to get dd/mm/yyyy.
Since yyyy-mm-dd string format is not culture dependent with the date data type, you can simply do this:
SELECT CONVERT(char(10), TRY_CAST(DateField As Date), 103) As [JobStartDate]
FROM tblTest
Note I've used try_cast and not cast since the database can't stop you from storing values that can't be converted to dates in that column.
You want to format the DateField column and not convert it to date.
So first convert it to DATE and then apply the format:
SELECT FORMAT(CONVERT(DATE, DateField, 21), 'dd/MM/yyyy') AS JobStartDate
See the demo.
I am trying to display the previous day's date Sybase using a select query:
select dateadd(day,-1,convert(char(10), getdate(), 23))
this query displays as 2015-06-18 00:00:00.0
I expect the output to be 2015-06-18.
How can I get that?
Try select dateadd(day,-1,convert(Date, getdate(), 365))
Try select convert(char(10),dateadd(day,-1, getdate() ), 23 )
Dateadd expects a date parameter as the third argument. In your example you're feeding it a char(10) . Even though implicit conversion from Char->DateTime is supported in Sybase, I would not code to depend on it in this case.
Well, datetime is a binary type. How it is formatted for display is up to you.
getdate() returns a datetime representing the current date/time. And dateadd() returns a datetime or date value, depending on what it started with (in your case, that would be datetime). And when you run your select statement, it's getting converted to a string using the default format configured for your Sybase instance. Hence your results.
In a nutshell, you are:
Converting the datetime value to char(10) to get an ISO 8601 format date string (yyyy-mm-dd).
Converting that back to a datetime value (so the time component is start-of-day)
Subtracting one day.
The easiest way to get what you want (yesterday's date) is this:
dateadd(day,-1, convert(date,getdate()) )
Which, when formatted for display, will come out as something like (depending on the default format configured for your Sybase instance) yyyy-mm-dd.
Or it might come out like November 29, 2015. If you want to ensure that it is an ISO 8601 date representation, you'll need to be explicit about it and cast it a char or varchar, thus:
convert(char(10) , dateadd(day,-1, convert(date,getdate()) ) , 23 )
which leaves you with a char(10) value containing yesterday's date.
If your version of Sybase doesn't support date, you'll have to fall back to what you were doing, but something like this:
convert(char(10) , dateadd(day,-1, getdate() ) , 23 )
You are telling it to give you hh:mm:ss, so that's what you are getting.
The 23 inside the convert is the format code for yyyy-mm-ddTHH:mm:ss There is no code to get yyyy-mm-dd, the closest you can get is 105 (dd-mm-yy) or 110 (mm-yy-dd).
If you need yyyy-mm-dd, then you'll have to convert the date to a string(char or varchar), and truncate the parts you don't want.
Converting Datetime
I have a ISO-8601 date in VARCHAR2 type, how can i convert that String date to timestamp in oracle db?
Date Example: "2014-09-12T11:53:06+00:00"
Maybe is something like the following but i not sure what is the format.
SELECT to_timestamp_tz ('2014-09-12T11:53:06+00:00', ????) FROM DUAL
The date format model elements are listed in the Datetime Format Models documentation:
SELECT to_timestamp_tz ('2014-09-12T11:53:06+00:00', 'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM')
FROM DUAL
TO_TIMESTAMP_TZ('2014-09-12T11:53:06+00:00','YYYY-MM-DD"T"HH24:MI:SSTZH:TZM')
---------------------------------------------------------------------------
12-SEP-14 11.53.06.000000000 +00:00
The fixed T can be included as a character literal:
You can include these characters in a date format model:
Punctuation such as hyphens, slashes, commas, periods, and colons
Character literals, enclosed in double quotation marks
TZH is tome zone hour, and TZM is time zone minutes. The rest are more common model elements.
I had an app that was making queries against an OracleDB database (19c).
The app was sending timestamp parameters in ISO 8601 format and the table had a column that was an Oracle TIMESTAMP type (not an Oracle TIMESTAMP WITH TIMEZONE type) that was just known to store timestamps that represented UTC time.
I thought the following query would work but it didn't seem to recognize the literals that were surrounded by double quotes:
SELECT * FROM measurements
WHERE measID = '333'
AND measTime > to_timestamp('2020-11-19T05:00:00Z', 'YYYY-MM-DD"T"hh:mm:ss"Z"');
-- Doesn't Work
-- ORA-01810: format code appears twice
-- 01810. 00000 - "format code appears twice"
The following did work for me:
SELECT * FROM measurements
WHERE measID = '333'
AND measTime > SYS_EXTRACT_UTC(TO_UTC_TIMESTAMP_TZ('2020-11-19T05:00:00Z'));
-- Works
Sharing because formatting ISO 8601 to TIMESTAMP types wasn't immediately clear in Oracle documentation.
I found this solution here:
https://oracle-base.com/articles/18c/to_utc_timestamp_tz-function-18c
I'm having a table IMAGEDATA in which the column VALUE stores datetime format in en-US (for ex. 06/08/2012 02:10:36 p.m.). I need to convert the datetime format to ISO8601 format (ex. 2012-08-22T13:10:39) for all the rows that are currently in the table. I'm novice in these topics. Could you please me some better approach it will be more helpful.Thanks.
Internally Datetime values are stored as 2 integers . They are not stored in the specific format in which they are inserted .In order to convert to 8601 format try the below code
Declare #date datetime
set #date = '06/08/2012 02:10:36 '
Select convert(varchar(30),#date,126)