T-SQL - Convert datetime to unseparated ISO value - sql

I'm trying to convert the following DATETIME into ISO format:
-- Today's Date
2018-04-16 2:04PM
I plan on parsing this into a char value as NVARCHAR so that I can concatenate it as part of a string.
Desired result should be:
-- Date and time unseparated
20180416140422
After some research I discovered here that
CONVERT(datetime, GETDATE(), 112)
using the 112 format code should get me the format I want but somehow I get the following sample output:
--Formatted using 112 format
Apr 16 2018 2:04PM
Why is this? I simply want to format the DATETIME object unseparated.
Also how would I do this with or without the time tagged onto the end?
Using SQL Server 2008R2

It should be :
select CONVERT(varchar(20), GETDATE(), 112)
Output
20180416
If you want date & time both, then can try using this :
select CONVERT(varchar(20), GETDATE(), 112) + replace(CONVERT(varchar(20), GETDATE(), 108), ':', '')
Output
20180416193327

Something like:
--20180416152520
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), GETDATE(), 121), '-', ''), ':', ''), ' ', '') AS DesiredFormat
Output:
20180416152520

Check this out:
SELECT CONVERT(varchar(20), GETDATE(), 112) AS ISODate
, CONVERT(varchar(50), GETDATE(), 126) AS ISOWithTime_WorksWithAnyLanguageSetting;
I believe the names of the columns are self-explanatory.
Output example:
ISODate | ISOWithTime_WorksWithAnyLanguageSetting
------------------------------------------------------
20180416 | 2018-04-16T15:26:50.607
For information on more formats of the CONVERT function with examples check this source.

These all seem a bit overly cumbersome when all you need is format():
select format(getdate(), 'yyyyMMddHHmmss') as ISODateTime;

Related

How to change datetime format in query?

My datetime column is in YYYYMMDDHHmmss format. Datasource of Grafana is SQL Server 2014 with read only access (TRIM() not valid).
How could I filter results in my query using Grafana time filter options?
I thought in using $__timeFrom() and $__timeTo(), but Grafana uses 2022-01-21T06:29:28Z format or unixepoch.
My query needs to convert:
2022-01-21T06:29:28Z -> 20220121062928
[EDIT]
Try 1 (it works):
WHERE s.zeitpunkt
BETWEEN
CAST(REPLACE(REPLACE(REPLACE(REPLACE($__timeFrom(), '-', ''), 'T', ''), ':', ''), 'Z', '') AS VARCHAR(25))
AND CAST(REPLACE(REPLACE(REPLACE(REPLACE($__timeTo(), '-', ''), 'T', ''), ':', ''), 'Z', '') AS VARCHAR(25))
Try 2 (it does not work):
WHERE s.zeitpunkt
BETWEEN CONCAT(
CONVERT(varchar, $__timeFrom(), 112)
, REPLACE(CONVERT(varchar, $__timeFrom(),108),':','')
)
AND CONCAT(
CONVERT(varchar, $__timeTo(), 112)
, REPLACE(CONVERT(varchar, $__timeTo(),108),':','')
)
If you are having trouble with date format of sql server you can do a number of things to change date format. For Example SSMS and SQL Server date format are decided by Your language and region set
You can use CAST(),CONVERT() to change the format of date or set your format from ssms.
You Can follow this link Date and Time Format in SQL
for datetime to datetimewith different formats
set language 'British'
cast(convert(varchar, getdate(), 103) as datetime)
This will change 2022-01-24 00:38:54.840 to 24/01/2022
This is what finally worked:
I Casted the datetime and used FORMAT() with a custom format. The other solutions I tried where a little bit slower.
WHERE s.zeitpunkt
BETWEEN
CAST(
FORMAT(CAST($__timeFrom() AS DATETIME),'yyyyMMddHHmmss')
AS VARCHAR)
AND CAST(
FORMAT(CAST($__timeTo() AS DATETIME),'yyyyMMddHHmmss')
AS VARCHAR)

Quicker way of converting from string with European date format to ISO dateformat

I wanted to ask if there is a quicker way of doing this:
CONVERT(NVARCHAR(10), CONVERT(date, '18.02.2016', 104), 112)
The following produces an error:
CONVERT(date, '18.02.2016', 112)
The entered string isn't style 112
SQL Server 2012 is used.
The first expression is the correct method, you could consider using char(10) instead.
This alternative method using FORMAT will be more flexible allowing other than the standard formats. FORMAT was introduced in sqlserver 2012.
SELECT FORMAT(CONVERT(date, '18.02.2016', 104), 'yyyyMMdd')
With this:
set dateformat dmy
select CONVERT(datetime, '18.02.2016')
the result is:
2016-02-18 00:00:00.000
So:
set dateformat dmy
select CONVERT(VARCHAR(10), CONVERT(datetime, '18.02.2016'), 112)
result is:
20160218

How to display the date as mm/dd/yyyy hh:mm Am/PM using sql server 2008 r2?

My sample query is
SELECT D30.SPGD30_LAST_TOUCH_Y
from CSPGD30_TRACKING D30
My given date format is like "2013-01-01 00:00:00.000". I need to convert this date format to "mm/dd/yyyy hh:mm AM/PM". Do you have any idea about that?
I think there is no single format to give them both. Try this using Convert; Sql-Demo
declare #mydate datetime = getdate()
select convert(varchar(10),#mydate, 101) + right(convert(varchar(32),#mydate,100),8)
| COLUMN_0 |
----------------------
| 02/22/2013 9:36AM |
The FORMAT() function is available from version 2012 onwards.
Once upgraded, you can use
select FORMAT(#date,'MM/dd/yyyy hh:mm:s tt')
Use this
select CONVERT(VARCHAR(10), mydate, 101) + ' ' + RIGHT(CONVERT(VARCHAR, mydate, 100), 7) from tablename
Try this
SELECT convert(varchar(20), GetDate(), 0);
To extract only AM/PM
substring(convert(varchar(30), GetDate(), 9), 25, 2);
Fiddle
Use the following scenario for getting date,time,day,month,year,hours,minutes,seconds,AM/PM
:)
SELECT UpdatedOn ,
CONVERT(varchar,UpdatedOn,100) DateTime,
CONVERT(varchar,UpdatedOn,10) Date ,
CONVERT(varchar,UpdatedOn,108) Time ,
substring(CONVERT(varchar,UpdatedOn,106),1,2) Day,
substring(CONVERT(varchar,UpdatedOn,106),4,3) CMonth,
substring(CONVERT(varchar,UpdatedOn,105),4,2) NMonth,
substring(CONVERT(varchar,UpdatedOn,106),8,4) Year,
left(right(CONVERT(varchar,UpdatedOn,100),7),2) Hours_12,
substring(CONVERT(varchar,UpdatedOn,108),1,2) Hours_24,
substring(CONVERT(varchar,UpdatedOn,108),4,2) Minutes,
substring(CONVERT(varchar,UpdatedOn,108),7,2) Second,
right(CONVERT(varchar,UpdatedOn,100),2) AM_PM
FROM dbo.DeviceAssignSim
WHERE AssignSimId=55;
You can do it like this:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
For more information look this:
date-format
Use the convert method to format a datetime value. Example:
select convert(varchar(20), D30.SPGD30_LAST_TOUCH_Y, 101)
The third parameter determines the format. You can find the available formats in the cast and convert documentation.
Use this
Select (Convert(Varchar,GetDate(),101))+' '+(Right(('0'+(LTrim((Left((Right((Convert(Varchar,GetDate(),100)),7)),5))))),5))+' '+(Right((Convert(Varchar,GetDate(),100)),2))
I realize this is a 8 year old question but it was answered in many ways and none are simple enough. This is what I found to be simple and matches just about what the user is asking for (year is two digits, and seconds are present), assuming that the date he is getting is from GETDATE(), not that it matters but that is where my answer comes from.
SELECT CONVERT(varchar, D30.SPGD30_LAST_TOUCH_Y, 22) AS [DateTime]
12/16/20 10:19:18 AM

how to format getdate into YYYYMMDDHHmmSS

In SQL Server how do I format getdate() output into YYYYMMDDHHmmSS where HH is 24 hour format?
I've got the YYYYMMDD done with
select CONVERT(varchar,GETDATE(),112)
but that is as far as I got.
Thanks.
Just for anyone searching for this functionality that has SQL Server 2012 you can use the FORMAT function:
SELECT FORMAT ( GETDATE(), 'yyyyMMddHHmmss') AS 'Custom DateTime'
This allows any .NET format strings making it a useful new addition.
select replace(
replace(
replace(convert(varchar(19), getdate(), 126),
'-',''),
'T',''),
':','')
Close but not exactly what you are asking for:
select CONVERT(varchar, GETDATE(), 126)
e.g.
2011-09-23T12:18:24.837
(yyyy-mm-ddThh:mi:ss.mmm (no spaces), ISO8601 without timezone)
Ref: CAST and CONVERT
There is no way to specify a custom format with CONVERT(). The other option is to perform string manipulation to create in the format you desire.
Try this:
select CONVERT(varchar, GETDATE(), 120)
e.g.
2011-09-23 12:18:24
(yyyy-mm-dd hh:mi:ss (24h) ,ODBC canonical).
Hth.
Another option!
SELECT CONVERT(nvarchar(8), GETDATE(),112) +
CONVERT(nvarchar(2),DATEPART(HH,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(MI,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(SS,GETDATE()));
converting datetime that way requires more than one call to convert. Best use for this is in a function that returns a varchar.
select CONVERT(varchar,GETDATE(),112) --YYYYMMDD
select CONVERT(varchar,GETDATE(),108) --HH:MM:SS
Put them together like so inside the function
DECLARE #result as varchar(20)
set #result = CONVERT(varchar,GETDATE(),112) + ' ' + CONVERT(varchar,GETDATE(),108)
print #result
20131220 13:15:50
As Thinhbk posted you can use select CONVERT(varchar,getdate(),20) or select CONVERT(varchar,getdate(),120) to get quite close to what you want.
select CONVERT(nvarchar(8),getdate(),112) +
case when Len(CONVERT(nvarchar(2),DATEPART(HH,getdate()))) =1 then '0' + CONVERT(nvarchar(2),DATEPART(HH,getdate())) else CONVERT(nvarchar(2),DATEPART(HH,getdate())) end +
case when Len( CONVERT(nvarchar(2),DATEPART(MI,getdate())) ) =1 then '0' + CONVERT(nvarchar(2),DATEPART(MI,getdate())) else CONVERT(nvarchar(2),DATEPART(MI,getdate())) end

SQL Server: How to get current date time in YYYYMMDDHHMISSMSS

I need the current date time in the format YYYYMMDDHHMISSMIS
Example:
20110723233747607
By using the CURRENT_TIMESTAMP or getdate() functions, we can retrieve the current datetime into 2011-07-23 23:37:47.607 format. If I use REPLACE and CONVERT functions to remove the "-" and ":" characters, then I get the value into
Jul 23 2011 11:37PM
...format. But I need the current date time as 20110723233747607 to use it for my another purpose.
My SQL query is:
SELECT REPLACE(CONVERT(VARCHAR(20), CURRENT_TIMESTAMP),'.','')
output: Jul 23 2011 11:37PM
So how can I get the current date time in my required format? Pls help.
select replace(
replace(
replace(
replace(convert(varchar(23), getdate(), 121),
'-',''),
'.',''),
' ',''),
':','')
I do not know why you need to use so many REPLACE() functions. Usage of functions really reduce the execution time. I used two CONVERT and one REPLACE function below.
SELECT CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(12), GETDATE(), 114),':','')