Convert regional string to datetimeoffset - sql-server

I have a date string in the following format:
9/28/2006 5:53:03 PM
I need to convert this to a format compatible with a datetimeoffset column (e.g. 2006-09-28 17:53:03 GMT).
I couldn't find any convert function to get this format. Looking either for Excel or SQL Server conversion.

To get the explicit string output you asked for in the question, you can do this, however that format is not compatible with datetimeoffset, mainly because GMT is invalid there.
DECLARE #string varchar(50) = '9/28/2006 5:53:03 PM';
SELECT CONVERT(varchar(50), CONVERT(datetime2(0), #string, 101)) + ' GMT';
String output:
2006-09-28 17:53:03 GMT
Since you actually don't seem to want the format you asked about at all and rather need to insert this value into a datetimeoffset column, then the explicit format you ask about in the question is irrelevant. Try (and not clear if all your times are in UTC and that's what you want, or if you really meant to translate to GMT, which observes DST IIRC):
DECLARE #string varchar(50) = '9/28/2006 5:53:03 PM';
DECLARE #dt datetimeoffset = CONVERT(datetime, #string, 101);
SELECT [UTC] = #dt,
[GMT] = #dt AT TIME ZONE 'GMT Standard Time';
Output
UTC
GMT
2006-09-28 17:53:03.0000000 +00:00
2006-09-28 18:53:03.0000000 +01:00
That should be compatible with your datetimeoffset column. Next time please explain the entire problem.
In either case, please don't use FORMAT() for this (as suggested in a comment), especially at scale.
FORMAT() is nice and all, but…
FORMAT is a convenient but expensive function, part 1
FORMAT is a convenient but expensive function, part 2

Related

Convert string timestamp in format yyyy-MM-ddTHH:mm:ss.ffffffZ to SQL Server datetime without changing time zone

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.

SQL Server date separator dot not working while inserting data

When I insert a date like this '01.03.2020 21:35:12' it changes into '2020-01-03 21:35:12.000'.
I want to insert the date with DOT as the Date separator.
NOTE: I'm not using a stored procedure, just insert query.
This is an inferior choice in format, because nobody reading that code can be certain whether you meant January 3rd or March 1st. You can get there this way, but it is ugly, unintuitive, and equally non-self-documenting:
DECLARE #d varchar(30) = '01.03.2020 21:35:12';
SELECT CONVERT(datetime, #d, 104);
Much better to use a standard, unambiguous date format for literals. These are the only two formats not subject to misinterpretation by language, dateformat, or regional settings, and therefore don't need to be accompanied by cryptic style numbers:
DECLARE #d1 varchar(30) = '20200301 21:35:12',
#d2 varchar(30) = '2020-03-01T21:35:12';
SELECT CONVERT(datetime, #d1), CONVERT(datetime, #d2);
Background:
Recommended SQL Server Date Formats
Bad Habits to Kick : Mis-handling date / range queries
Dating Responsibly
I don't think you can change the display in SSMS from the YYYY-MM-DD TIME format. If you want to change the way you get the date back when selected, you can use the CONVERT or FORMAT functions.
CONVERT function: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
FORMAT function: https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql
You may need to select your datetime twice with the CONVERT. Once for the date and once for the time in order to get the combination of formats you want.
-John

How to only keep the time portion of a datetime value (SQL Server)?

Here's what I use to get a HH:MM string:
CONVERT(varchar(5), time_requested, 108)
I'm thinking there may be a more elegant way, even maybe more efficient (see similar question on How to remove the time portion of a datetime value (SQL Server)?).
Requirements:
the final result has to be easily convertible to a string (in order to be able to concatenate some field time_created with a field such as date_created).
the following 2 cases must be covered: HH:MM and HH:MM:SS.
Declare #D datetime = GetDate() -- Data Type could be Time as well
Select CONVERT(varchar(8), #D, 108) -- for HH:MM:SS 11:27:26
Select CONVERT(varchar(5), #D, 108) -- for HH:MM 11:27
Failed to mention, if 2012+ you could also use Format()
Declare #D DateTime = '2016-10-22 13:30:25'
Select Format(#D,'HH:mm') -- 13:30
Select Format(#D,'hh:mm:ss tt') -- 01:30:25 PM
Your method is fine. It produces a string representation of the value.
You can also convert to a time data type:
select cast(time_requested as time)
But note that this is "format-less" -- it contains hours, minutes, seconds, and fractions of seconds. So, your method is probably the better approach.

How to convert a datetime to string in T-SQL

I'm surprised not to be able to find this question here already.
I have a date time var and I want to convert it to a string so that I can append it to another string. I want it in a format that can be converted easily back to a date time.
How can I do this?
(I want the date part and the time part.)
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
SQLFiddle Demo
SQL Server Date Formats
There are many different ways to convert a datetime to a string. Here is one way:
SELECT convert(varchar(25), getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
See Demo
Here is a website that has a list of all of the conversions:
How to Format datetime & date in SQL Server
In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.
To convert back, use the opposite PARSE or TRYPARSE functions.
The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.
DECLARE #DateTime DATETIME2 = SYSDATETIME();
DECLARE #StringResult1 NVARCHAR(100) = FORMAT(#DateTime, 'g') --without culture
DECLARE #StringResult2 NVARCHAR(100) = FORMAT(#DateTime, 'g', 'en-gb')
SELECT #DateTime
SELECT #StringResult1, #StringResult2
SELECT PARSE(#StringResult1 AS DATETIME2)
SELECT PARSE(#StringResult2 AS DATETIME2 USING 'en-gb')
Results:
2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000
SELECT CONVERT(varchar, #datetime, 103) --for UK Date format 'DD/MM/YYYY'
101 - US - MM/DD/YYYY
108 - Time - HH:MI:SS
112 - Date - YYYYMMDD
121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF
20 - ODBC - YYYY-MM-DD HH:MI:SS
There are 3 different methods depending on what I is my requirement and which version I am using.
Here are the methods..
1) Using Convert
DECLARE #DateTime DATETIME = GETDATE();
--Using Convert
SELECT
CONVERT(NVARCHAR, #DateTime,120) AS 'myDateTime'
,CONVERT(NVARCHAR(10), #DateTime, 120) AS 'myDate'
,RIGHT(CONVERT(NVARCHAR, #DateTime, 120),8) AS 'myTime'
2) Using Cast (SQL Server 2008 and beyond)
SELECT
CAST(#DateTime AS DATETIME2) AS 'myDateTime'
,CAST(#DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
,CAST(#DateTime AS DATE) AS 'myDate'
,CAST(#DateTime AS TIME) AS 'myTime'
,CAST(#DateTime AS TIME(3)) AS 'myTimeWithPrecision'
3) Using Fixed-length character data type
DECLARE #myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, #DateTime, 120);
DECLARE #myDate NVARCHAR(10) = CONVERT(NVARCHAR, #DateTime, 120);
SELECT
#myDateTime AS 'myDateTime'
,#myDate AS 'myDate'
You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
Check CAST and CONVERT syntax of t-sql:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Try below :
DECLARE #myDateTime DATETIME
SET #myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, #myDateTime, 120), 10)
This has been answered by a lot of people, but I feel like the simplest solution has been left out.
SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here
Look at the section on "Supported string literal formats for datetime2"
To answer the OPs question explicitly:
DECLARE #myVar NCHAR(32)
DECLARE #myDt DATETIME2
SELECT #myVar = #GETDATE()
SELECT #myDt = #myVar
PRINT(#myVar)
PRINT(#myDt)
output:
Jan 23 2019 12:24PM
2019-01-23 12:24:00.0000000
Note:
The first variable (myVar) is actually holding the value '2019-01-23 12:24:00.0000000' as well. It just gets formatted to Jan 23 2019 12:24PM due to default formatting set for SQL SERVER that gets called on when you use PRINT. Don't get tripped up here by that, the actual string in (myVer) = '2019-01-23 12:24:00.0000000'
In the stored procedure for me works something like this.
convert(varchar(10), StartingDate) AS 'StartingDate'

Correct way of specifying a given date in T-SQL

I am writing some T-SQL which needs to enforce a minimum date value onto some null fields:
DECLARE #epoch DATETIME;
set #epoch='1900-01-01';
select min = ISNULL(ValidFromDate,#epoch)
Is the string '1900-01-01' always going to return a datetime of Jan 1 1900 in any environment or will SQL server try to parse the string according to local culture rules?
If that's not good enough, what is the recommended way of specifying a particular date/time in T-SQL?
The best format for string-based dates is the ISO-8601 standard format.
For DATETIME variables and columns, this is either YYYYMMDD (for dates without time; without any dashes!) or YYYY-MM-DDTHH:MM:SS (date + time).
Contrary to popular belief, YYYY-MM-DD for DATETIME variables is NOT language-/dateformat-independent! If you try this, the second CAST will result in an error:
SET LANGUAGE us_english
SELECT CAST('2011-07-20' AS DATETIME)
SET LANGUAGE british
SELECT CAST('2011-07-20' AS DATETIME)
but this will work:
SET LANGUAGE british
SELECT CAST('20110720' AS DATETIME)
This is the best format since it's indepdendent of your language and dateformat settings in SQL Server.
For SQL Server 2008 and columns of type DATE (just date - no time), the format can also be YYYY-MM-DD (with the dashes) and that works for all settings, too.
Why there is such a difference between DATE and DATETIME is beyond me - that's just the way it is for now!
See Tibor Karaszi's excellent The Ultimate Guide to the DateTime data types for even more details and examples.

Resources