Convert datetime to specific format in SQL Server - sql

How to convert datetime to this format : 2019/06/17 18:00:00.123
I use select convert(varchar, getdate(), 111) and select convert(varchar, getdate(), 108) together but I get only 2019/06/17 18:00:00
I can't find a combination to get format I need. Is there any way to get it?

You could use FORMAT to return the DATETIME in a specified format (assuming you use SQL-Server and want to return a string type).
DECLARE #example DATETIME = GETDATE();
SELECT FORMAT(#example, 'yyyy/MM/dd HH:mm:ss.fff');

use datetime2 data type and cast getdate to datetime2(3) for 3 digit precesion
select cast( getdate() as DATETIME2(3))

Related

Out-of-range value when converting dates separated by dots

How can I convert the following VARCHAR(50) data:
01.01.2020 06:10:15
to a DateTime?
Assuming that the dates are in dd.mm.yyyy format, you can use the date and time style #104 (German) that uses this exact format:
SELECT CONVERT(DATETIME, '13.01.2020 06:10:15')
-- The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
SELECT CONVERT(DATETIME, '13.01.2020 06:10:15', 104)
-- 2020-01-13 06:10:15.000
You can try the below method:
SELECT CONVERT(datetime, '2017-08-25')
in place of the date under singled quotes you can place the variable name.
Try Below Code :
select convert(datetime, '01.01.2020 06:10:15', 104)
Help Link
You can achieve by this way
Declare #Str VARCHAR(50) = '01.01.2020 06:10:15'
Select CONVERT(date, REPLACE(#Str, '.', '/'), 103)

I need to convert this string to datetime in SQL Server

String:
'01/04/2019 01:50:31.230000000'
Expected result:
01/04/2019 01:50:31.230
as a DATETIME.
Query used:
SELECT CONVERT(DATETIME, '01/04/2019 01:50:31.230000000', 113)
Converting that string, which is in the 103 format, would work if it didn't have the last 6 zero's.
So a SUBSTRING or LEFT could be used to keep only 23 characters.
And then convert it to a DATETIME.
But that string, can be converted just fine to a DATETIME2.
Since a DATETIME2 is more accurate.
And a DATETIME2 can be simply casted or converted to a DATETIME.
Note that DATETIME isn't stored with a format in the table.
The way it's displayed is a setting.
However, you can FORMAT a DATETIME back to a string in the specific format you need. (starting with SQL Server 2012)
Example snippet:
select
col as col_input_string,
CAST(CONVERT(datetime2, col, 103) AS datetime) as col_as_datetime,
FORMAT(CONVERT(datetime2, col, 103), 'dd/MM/yyyy HH:mm:ss.fff') as col_as_formatted_string
from (values
('01/04/2019 01:50:31.230000000')
,('31/12/2018 13:33:44.123456789')
) q(col);
Result:
col_input_string col_as_datetime col_as_formatted_string
01/04/2019 01:50:31.230000000 2019-04-01 01:50:31.230 01/04/2019 01:50:31.230
31/12/2018 13:33:44.123456789 2018-12-31 13:33:44.123 31/12/2018 13:33:44.123
The code you want is:
SELECT CONVERT(datetime,LEFT('01/04/2019 01:50:31.230000000',23),103);
You need to use LEFT as datetime is only accurate to 1/300 of a second; thus you need to trim off the accuracy that can't be used.
Try to use
declare #vardate varchar(50) = '01/04/2019 01:50:31.230000000'
declare #date datetime =convert(date, left(#vardate,23), 103)
declare #time time = convert(time, substring(#vardate,12,12), 14)
select DATEADD(DAY, DATEDIFF(DAY, #time, #date), CAST(#time AS DATETIME)) AS Result
if that does not work check different convert formats.

How to convert string date into valid date format in SQL Server 2008?

I have string date in yymmdd format, for example 150202
I want to convert this string into a valid date in format yyyymmdd, e.g. 20150202.
Thanks in advance.
convert your string to datetime and then do that you want with it
declare #dt varchar(6) = '150213'
select CONVERT(datetime, #dt, 112)
Do another CONVERT to transform it to yyyymmdd format.
SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, #dt, 112), 112)
may this will work
select CONVERT(datetime, '150202', 112)
for all date conversions
http://www.sqlusa.com/bestpractices/datetimeconversion/
instead of select CONVERT(datetime, '150202', 112)
its better to use "select TRY_CONVERT(datetime, '150202', 112)"
while using try_convert if there is any error it will returns null,if we are using convert it will returns error when conversion fails.

Convert format of date

I have a date format like
'2003-11-27 00:00:00.000'
How can I convert it into YYYYMMDD like 20031127 WITH SQL SERVER ?
To convert the date as per ISO standard you can write as:
SELECT CONVERT (VARCHAR(8), GETDATE(),112) as [YYYYMMDD]
SELECT CONVERT (VARCHAR(8), cast('2003-11-27 00:00:00.000' as datetime), 112)
It depends of how your date is declared.
DECLARE #date datetime = '2003-11-27T00:00:00.000' -- datetime
DECLARE #date2 char(23) = '2003-11-27 00:00:00.000' -- char(23)
SELECT
convert(char(8), #date, 112) datetimeconvert,
convert(char(8), convert(datetime, #date2, 121), 112) charconvert
Result:
datetimeconvert charconvert
20031127 20031127
The date types in SQL Server do not have any format, they are binary types. Formats apply only when you convert them to text or try to parse a text literal.
You don't specify what is the value you posted, or what you want to do with it. There are several possibilities:
You want to truncate the time portion of a datetime field. Then just cast(myField as date)
You want to create a text string containing the date portion of a datetime or date field: FORMAT(myField,'yyyyMMdd') or CONVERT(varchar(8),myField,112). FORMAT provides almost as much flexibility as .NET's String.Format but in this case CONVERT it's enough.
You want to convert one text literal to another: FORMAT(CONVERT(date,'2003-11-27 00:00:00.000',121),'yyyyMMdd'). You convert the original string to a date then format it as you wish.

Combining (concatenating) date and time into a datetime

Using SQL Server 2008, this query works great:
select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field
Gives me two columns like this:
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
.
.
.
I'm trying to combine them into a single datetime using the plus sign, like this:
select CAST(CollectionDate as DATE) + CAST(CollectionTime as TIME)
from field
I've looked on about ten web sites, including answers on this site (like this one), and they all seem to agree that the plus sign should work but I get the error:
Msg 8117, Level 16, State 1, Line 1
Operand data type date is invalid for add operator.
All fields are non-zero and non-null. I've also tried the CONVERT function and tried to cast these results as varchars, same problem. This can't be as hard as I'm making it.
Can somebody tell me why this doesn't work? Thanks for any help.
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate and CollectionTime to char sequences, combine them, and then convert them to a datetime.
The parameters to CONVERT are data_type, expression and the optional style (see syntax documentation).
The date and time style value 112 converts to an ISO yyyymmdd format. The style value 108 converts to hh:mi:ss format. Evidently both are 8 characters long which is why the data_type is CHAR(8) for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss and then converted to a datetime.
The simple solution
SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field
An easier solution (tested on SQL Server 2014 SP1 CU6)
Code:
DECLARE #Date date = SYSDATETIME();
DECLARE #Time time(0) = SYSDATETIME();
SELECT CAST(CONCAT(#Date, ' ', #Time) AS datetime2(0));
This would also work given a table with a specific date and a specific time field. I use this method frequently given that we have vendor data that uses date and time in two separate fields.
Cast it to datetime instead:
select CAST(CollectionDate as DATETIME) + CAST(CollectionTime as TIME)
from field
This works on SQL Server 2008 R2.
If for some reason you wanted to make sure the first part doesn't have a time component, first cast the field to date, then back to datetime.
DECLARE #ADate Date, #ATime Time, #ADateTime Datetime
SELECT #ADate = '2010-02-20', #ATime = '18:53:00.0000000'
SET #ADateTime = CAST (
CONVERT(Varchar(10), #ADate, 112) + ' ' +
CONVERT(Varchar(8), #ATime) AS DateTime)
SELECT #ADateTime [A nice datetime :)]
This will render you a valid result.
Solution (1): datetime arithmetic
Given #myDate, which can be anything that can be cast as a DATE, and #myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:
CAST(CAST(#myDate as DATE) AS DATETIME) + CAST(CAST(#myTime as TIME) as DATETIME)
You can verify with:
SELECT GETDATE(),
CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)
Solution (2): string manipulation
SELECT GETDATE(),
CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))
However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.
See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation
Concat date of one column with a time of another column in MySQL.
SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
drop table test
create table test(
CollectionDate date NULL,
CollectionTime [time](0) NULL,
CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)
insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
('2013-12-10', null),
(null, '22:51:19.227')
select * from test
CollectionDate CollectionTime CollectionDateTime
2013-12-10 22:51:19 2013-12-10 22:51:19.000
2013-12-10 NULL 2013-12-10 00:00:00.000
NULL 22:51:19 NULL
This works in SQL 2008 and 2012 to produce datetime2:
declare #date date = current_timestamp;
declare #time time = current_timestamp;
select
#date as date
,#time as time
,cast(#date as datetime) + cast(#time as datetime) as datetime
,cast(#time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,#date) - 1,dateadd(year,datepart(year,#date) - 1900,cast(#time as datetime2))) as datetime2;
dealing with dates, dateadd must be used for precision
declare #a DATE = getdate()
declare #b time(7) = getdate()
select #b, #A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, #a), cast(#b as datetime2(0)))
I am using SQL Server 2016 and both myDate and myTime fields are strings. The below tsql statement worked in concatenating them into datetime
select cast((myDate + ' ' + myTime) as datetime) from myTable
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), date, 112) + ' ' + CONVERT(CHAR(8), time, 108))
FROM tablename