SQL convert datetime to varchar - sql

I want to convert DATETIME to VARCHAR (month/day/year) like this:
10/09/2018 12:00:00.000
I tried using
Convert(VARCHAR(MAX),[Date & Time Added]),121)
but it returns
yyyy-mm-dd hh:mi:ss.mmm
I need the / format with time, I am Using SQL Server 2012.

You can use the FORMAT function:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy HH:mm:ss.fff')
-- 10/09/2018 00:58:52.557
Complete list of format specifiers is actually available in the .NET documentation.
If FORMAT function is unavailable you could simply format in a known format and use string functions to re-arrange the year, month, day and time parts. For example:
SELECT SUBSTRING(DateStr, 6, 2) + '/' + SUBSTRING(DateStr, 9, 2) + '/' + SUBSTRING(DateStr, 1, 4) + ' ' + SUBSTRING(DateStr, 12, 12)
FROM (
SELECT CONVERT(VARCHAR(23), GETDATE(), 126) -- ISO8601 / yyyy-mm-ddThh:mi:ss.mmm
) AS CA(DateStr)
-- 10/09/2018 01:12:50.833
SELECT CONVERT(VARCHAR(10), Date, 101) + ' ' + CONVERT(VARCHAR(12), Date, 114)
FROM (
SELECT GETDATE()
) AS CA(Date)
-- 10/09/2018 01:19:38:463

This is something that would usually be done in the presentation layer, but if you need to do it in the data layer you can use FORMAT (documentation here)
Syntax is: FORMAT ( value, format [, culture ] )
So in your case (edited to add AM/PM designation per your comments): FORMAT([Date & Time Added], 'dd/MM/yyy hh:mm:ss.fff tt')
Custom date format string options are detailed here

Related

Convert data and time into a numeric number in sql server

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000
So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.
Any one knows how to do it please?
You can use the FORMAT function:
SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')
By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:
DECLARE #d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), #d, 112) + REPLACE(CONVERT(NVARCHAR(8), #d, 8), ':', '') + '00000' AS BIGINT)

convert date yyyy-mm-dd to mmm-yy SQL Server 2016

I want to convert date yyyy-mm-dd (stored as a date format) to mmm-yy format.
There are no exact matches in the prior questions on the site.
I have tried substrings and convert function, was considering creating a scalar function but its taking me a while and hoping someone has an easy solution.
You can construct the format using string operations:
select left(datename(month, datecol), 3) + '-' + right(datename(year, datecol), 2)
Or using format():
select format(datecol, 'MMM-yy')
Try this
select replace(right(convert(varchar(9), getdate(), 6), 6), ' ', '') asDate

Convert nvarchar date (DD/MM/YYYY) to Date Period (YYYY_MM)

I am trying to convert this into a period format, so e.g. 2018_05 (YYYY_MM). currently the data is in DD/MM/YYYY format.
I tried a cast code but it returns me YYYY_DD.
SELECT
CASE WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE cast(year(RESERVED_FIELD_4) as Nvarchar (4))
+'_'+right('00'+cast(month(RESERVED_FIELD_4) as Nvarchar (2)),2)
END AS [DATAFEED_PERIOD]
I expect/want to see YYYY_MM.
Assuming RESERVED_FIELD_4 is a string type (char/nchar/varchar/nvarchar) the simplest solution would be to use substring:
CASE
WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE SUBSTRING(RESERVED_FIELD_4, 7, 4) + '_'+ SUBSTRING(RESERVED_FIELD_4, 4, 2)
END AS [DATAFEED_PERIOD]
If it's a date/datetime/datetime2 data type, the simplest solution would be to use format:
FORMAT(RESERVED_FIELD_4, 'yyyy_MM')
But for better performance you can use convert and stuff:
SELECT STUFF(CONVERT(char(6), RESERVED_FIELD_4, 112), 5, 0, '_')
In case your format is actually d/m/y the simplest option is to convert to date and than back to string:
SELECT STUFF(CONVERT(char(6), CONVERT(Date, RESERVED_FIELD_4, 103), 112), 5, 0, '_')
This is the common problem of storing a date with a VARCHAR column. You are guessing that the stored pattern is DD/MM/YYYY but the SQL engine doesn't know that and is currently assuming the MM/DD/YYYY pattern.
Please check these results:
-- MM/DD/YYYY
SELECT
DAY ('05/01/2019'), -- 1
MONTH('05/01/2019') -- 5
-- DD/MM/YYYY
SELECT
DAY ('25/05/2019'), -- Conversion failed when converting date and/or time from character string
MONTH('25/05/2019') -- Conversion failed when converting date and/or time from character string.
To display what you want correctly use string functions:
SELECT
RIGHT(RESERVED_FIELD_4, 4) + '_' + SUBSTRING(RESERVED_FIELD_4, 4, 2)
But you should actually fix the values on your VARCHAR column, cast them to DATE and store the values as DATE.
ALTER TABLE YourTable ADD ReservedField4Date DATE
UPDATE YourTable SET
ReservedField4Date = CONVERT(DATE,
RIGHT(RESERVED_FIELD_4, 4) -- Year
+ '-' + SUBSTRING(RESERVED_FIELD_4, 4, 2) -- Month
+ '-' + LEFT(RESERVED_FIELD_4, 2)) -- Day
ALTER TABLE YourTable DROP COLUMN RESERVED_FIELD_4
EXEC sp_rename 'SchemaName.YourTable.ReservedField4Date', 'RESERVED_FIELD_4', 'COLUMN'
Beware that changing the column type might affect other queries that assume this is a VARCHAR column.
If your data is in DD/MM/YYYY format, then it is being stored as a string. Hence, string functions come to mind:
select right(RESERVED_FIELD_4) + '_' + substrint(RESERVED_FIELD_4, 4, 2)
In SQL-SERVER you can use 'format'
format(dy,#your_date) as day_of_year
month(#your_date) as month
Try this:
Select concat(month(#your_date),'_'year(#your_date)) as your_period
this is a reference
Why not just do conversations ? :
SELECT REPLACE(CONVERT(VARCHAR(7), CONVERT(date, RESERVED_FIELD_4, 101), 102), '.', '_')
This assumes RESERVED_FIELD_4 is date type.

How to convert 13 digit timestamp to date and time format in mssql

I am trying to store 13 digit timestamp to store date time format in MS SQL table.
I have tried in many ways and also searched in SO posts nothing is helped for me.
Input Code : 1525939481255
Required Format : DD-MM-YYYY HH:MM:SS (12 hour time format)
I want to convert the above 13 digit code to the above mentioned format.
Can anyone help me to solve this ?
I assuming that was unix time in miliseconds
so try this query
select CONVERT(VARCHAR(10),DATEADD(SECOND, 1525939481255/1000 ,'1970/1/1'),105)
I'm sorry, i miss the time format,
Try this one..
select CONVERT(VARCHAR(10),DATEADD(SECOND, 1525939481255/1000 ,'1970/1/1'),105) + ' ' + FORMAT(DATEADD(SECOND, 1525939481255/1000 ,'1970/1/1'),'h:mm:ss tt')
CMIIW,
please let me know, if this help..
The UNIX time can be convert to normal datetime and will be format to your expected format as:
DECLARE #DateValue AS BIGINT = 1525939481255;
SELECT CONVERT(VARCHAR(10), DATEADD(SECOND, #DateValue/1000 ,'1970/1/1'), 105) + ' ' +
CONVERT(VARCHAR(15), CAST(DATEADD(SECOND, #DateValue/1000 ,'1970/1/1') AS TIME), 100)
output:
10-05-2018 8:04AM
Try this:
declare varchar(max) myDateTime = select dateadd(second, 1525939481255/1000 + 8*60*60, '19700101');
SELECT REPLACE(
REPLACE(
RIGHT(
'0000000000' +
CONVERT(
varchar(10),
cast(myDateTime as time(0)),
109),
10),
'PM',
' p.m.'),
'AM',
' a.m.') as 'Time'
, reverse(Left(myDateTime, 10)) as 'date'

SQL Converting string MMM.YY to date

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!
I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.
If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')