Convert Nvarchar DD/MM/YYYY to YYYY-MM-DD in SQL Query - sql

Hi I have a column in my 'Users' table called 'PersonalDetails_DOB'.
The data type is a NVARCHAR(10) and the 'format' the data is currently in DD/MM/YYYY.
I want to change the format to YYYY.MM.DD or YYYY-MM-DD, how would I do this?
I have already tried a running a query in SQL:
SELECT CONVERT(nvarchar(10), PersonalDetails_DOB, 102) as
'PersonalDetails_DOB' FROM Users;
Nothing happens and it doesn't change any date from e.g. 06/02/1967 to 1967.02.06

You need two convert() function :
SELECT PersonalDetails_DOB,
CONVERT(VARCHAR(10), CONVERT(DATE, PersonalDetails_DOB, 103), 102)
FROM Users;

Store dates as dates, not strings. I recommend you pull the value as a date and not a string:
SELECT CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;
You are safer using try_convert():
SELECT TRY_CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;
To find the bad values, you can do:
select PersonalDetails_DOB
from users
where TRY_CONVERT(date, PersonalDetails_DOB, 103) is null;
You can convert back a string if you want.
I would recommend that you fix the data structure. This should work:
update users
set PersonalDetails_DOB = CONVERT(date, PersonalDetails_DOB, 103);
alter users alter column PersonalDetails_DOB date;

You can try the below query to update the date values format and also their data type using SUBSTRING() function as shown below
declare #PersonalDetails_DOB NVARCHAR(10)
set #PersonalDetails_DOB = '13/10/2018' --dd/MM/yyyy
select SUBSTRING(#PersonalDetails_DOB,7,4) + '-' + SUBSTRING(#PersonalDetails_DOB,4,2)
+ '-' + SUBSTRING(#PersonalDetails_DOB,1,2)
-- yyyy-MM-dd
create table Users(PersonalDetails_DOB NVARCHAR(10))
insert into Users values ('01/10/2018')
select * from Users --Before Update
--Updating date values
update Users
set PersonalDetails_DOB = (
SUBSTRING(#PersonalDetails_DOB,7,4) + '-' + SUBSTRING(#PersonalDetails_DOB,4,2)
+ '-' + SUBSTRING(#PersonalDetails_DOB,1,2)
)where PersonalDetails_DOB is not null
select * from Users --After Update
--Change the datatype
ALTER TABLE Users
ALTER COLUMN PersonalDetails_DOB date;
You can find the live demo Live Demo Here

Maybe you should first set dateformat before conversion:
set dateformat dmy;
select PersonalDetails_DOB
,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 102) as ANSI_DOB
,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 120) as ODBC_DOB
from Users;

Related

How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?

I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format.
I've already tried convert which only works for one of the two formats but not both:
declare #string nvarchar(255) = '2019-05-21'
declare #table table (date date)
insert into #table
select convert(date, #string, 111) as date
select * from #table
declare #string nvarchar(255) = '21/05/2019'
declare #table table (date date)
insert into #table
select convert(date, #string, 103) as date
select * from #table
Both of the above solutions result in an error is I use the other format.
Is there a way to get a string converted to date regardless of what format it is in?
Use try_convert():
insert into #table
select coalesce(try_convert(date, #string, 111),
try_convert(date, #string, 103)
) as date
try_convert() returns NULL if the conversion fails. In that case, the conversion will move on to the next pattern. With coalesce(), you can have as many different formats as you like.
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture.
The second format YYYY-MM-DD is an unambiguous date format for the "new" date types like date and datetime2. It's not affected by the DATEFORMAT setting like datetime.
This means you only need to find one culture that can handle the first format. All of the following queries will return the same value :
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function.
The signature of this function is - FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

DATETIME SQL Query

I am using SQL Server 2008 Management Studio. I have a datetime column in my table.
When I select all contents of the table, the date column has data like 10/10/2013 12:00:00 AM.
I need a query to display all contents from the table with date column data as 10/10/2013.
SELECT CONVERT(VARCHAR(10), column, 101) -- u.s standard format mm/dd/yyyy
SELECT CONVERT(VARCHAR(10), column, 103) -- British/French standard format dd/mm/yyyy
Try this one (2008 and higher) -
SELECT CAST('10/10/2013 12:00:00 AM' AS DATE)
For 2005 -
SELECT CAST('10/10/2013 12:00:00 AM' AS VARCHAR(10))
Output -
10/10/2013
This will help you
cast(floor(cast(#dateVariable as float)) as datetime)
Using CONVERT function along with styles for DATETIME you can choose the way dates are displayed. 101 would give you mm/dd/yyyy, 103 = dd/mm/yyyy
SELECT CONVERT(NVARCHAR(20),your_datetime_col, 103) FROM your_table
SQLFiddle DEMO
You can use FORMAT() function:
SELECT FORMAT(<your_column>, 'MM/dd/YYYY') FROM <your_table>;
For your question i was created one table as
create table dateverify(date_v varchar(20));
Inserted single column value
declare #a varchar(20);
set #a='10/10/2013';
begin
insert into dateverify(date_v) values(#a);
end;
using below query,
SELECT CONVERT(VARCHAR(20), date_v , 103) AS [DD/MM/YYYY] from dateverify;
got an answer like you are asked..10/10/2013

How to convert a timestamp (DATE FORMAT) to BIGINT in SQL

I need to convert the timestamp value (Format: 2012-11-19 14:29:50.0) to a BIGINT value (Format: 2012111315041650 = YYYYMMDDhhmmss). I need to insert current time in a column of a table which accepts only BIGINT.
I am using Squirrel SQL Client Version 3.3.0. The query I am using right now is
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES (2012111315041650, CURRENT_TIMESTAMP);
Instead of manually entering the BIGINT_DATE value, I want to convert the CURRENT_TIMESTAMP or NOW() to a BIGINT value as the format YYYYMMDDHHMISS
Something like
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES ("CONVERT(CURRENT_TIMESTAMP,BIGINT)", CURRENT_TIMESTAMP);
Let me know if it is feasible to do this way
Please help me with this.
Thanks
For Postgres you can use:
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES (to_char(current_timestamp, 'yyyymmddhh24miss')::bigint, CURRENT_TIMESTAMP);
To convert timestamp values to bigint values (in seconds) you can do it in this way:
SELECT (EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::bigint -- -> 1554216999
To convert timestamp values to bigint values (in millis) you can do it in this way:
SELECT ((EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::numeric * 1000)::bigint -- -> 1554216999009
If you want to convert all timestamp values of a column into a table into another column of the same table you can run this query (result in millis):
UPDATE $table_name$ SET $column_with_values_bigint$ = (EXTRACT(EPOCH FROM $column_with_values_timestamp$)::numeric * 1000)::bigint
Hope this help.
For Oracle: Use to_char and to_number functions as below
TO_NUMBER(TO_CHAR('2012-11-19 14:29:50.0', 'YYYYMMDDHHMISS'))
For MySQL: Use DATE_FORMAT & CONVERT as below:
CONVERT(DATE_FORMAT('2012-11-19 14:29:50.0'', '%Y%M%d%H%i%s'), UNSIGNED BIGINT)
The following will give you what (I think) you are after:
DECLARE #TM VARCHAR(50) = '2012-11-19 14:29:50.0'
SELECT (CAST(SUBSTRING(#TM,1,4) AS INT) * 10000000000)
+ (CAST(SUBSTRING(#TM,6,2) AS INT) * 100000000)
+ (CAST(SUBSTRING(#TM,9,2) AS INT) * 1000000)
+ (CAST(SUBSTRING(#TM,12,2) AS INT)* 10000)
+ (CAST(SUBSTRING(#TM,15,2) AS INT)* 100)
+ (CAST(SUBSTRING(#TM,18,2) AS INT))
However there may be a better solution to the overall problem which others have mentioned, if you give some more details we might be able to suggest a less dirty alternative.
you can try something like that on MS SQL:
From bigint to datetime:
select dateadd(s, convert(bigint, '<bigint value like 1477958400000>') / 1000, convert(datetime, '1-1-1970 00:00:00'))
From datetime to bigint:
select cast(datediff(s, convert(datetime, '1-1-1970 00:00:00'), convert(datetime, '<datetime value like 11-01-2016>')) as bigint)* 1000
Cheers
DATETIME to BIGINT;
SELECT CONVERT(BIGINT, FORMAT(CURRENT_TIMESTAMP, 'yyyyMMddHHmmss'))
OR
SELECT CONVERT(BIGINT, FORMAT(GETDATE(), 'yyyyMMddHHmmss'))
BIGINT to DATETIME;
SELECT CONVERT(DATETIME, FORMAT(20191220213340, '####-##-## ##:##:##'))
Sql Server; Replace GETDATE() With your Column name
SELECT CONVERT(bigint,
CONVERT(VARCHAR(12) , GETDATE() ,112) +
REPLACE(CONVERT(VARCHAR(8) , GETDATE() ,108),':',''))

How do I convert hh:mm:ss to hh:mm in SQL Server?

How do I convert hh:mm:ss to hh:mm in SQL Server?
select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog
where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58'
and [user] in(select USERNAME
from scr_CustomerAuthorities )
group by Page,Date order by [VisitingCount] asc
CONVERT(VARCHAR(5),Date, 108)-- Gets only HH:mm
In general, the set of timestamps is not well-ordered, this means you cannot get a "last" timestamp whose time part up to minutes is 2009-05-06 14:58.
In SQL Server, which keeps the time part of a datetime as a number of 1/300 second fractions after midnight, this "last" timestamp would be 2009-05-06 14:58:59.997, but this is not guaranteed to be compatible with future releases of with other TIMESTAMP storage methods.
That means you'll need to split your BETWEEN condition into two conditions, one of which being strict less than the next minute:
select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog
where Date >= '2009-05-04 00:00:00'
AND Date < DATEADD(minute, 1, '2009-05-06 14:58')
and [user] in(select USERNAME
from scr_CustomerAuthorities )
group by Page,Date order by [VisitingCount] asc
This solution will efficiently use indexes on Date
SELECT Convert(varchar(5), GetDate(), 108)
Using varchar(5) will automatically truncate the date to remove the seconds.
I dont think there is a built in function; usually do something like this
SET #time = '07:45'
SET #date = CONVERT(DATETIME,#time)
SELECT #date
SELECT LEFT(CONVERT(VARCHAR,#date,108),5)
For this specific need you should use the between method as noted by Quassnoi's answer. However, the general problem can be solved with:
select dateadd(second, -datepart(second, #date), #date)
One way would be to use the RIGHT() function to crop the Date. Something like:
RIGHT(CONVERT(VARCHAR(8),Date, 108),5)
This will only work if number of characters is constant e.g. there is a leading zero if applicable. (Sorry havn't got SQL server here to test).
A better way is to use the T-SQL datepart function to split and then re-concatinate the date parts so:
DARTPART("hh", CONVERT(VARCHAR(8),Date, 108))+":"+DARTPART("mi", CONVERT(VARCHAR(8),Date, 108))
References:
http://msdn.microsoft.com/en-us/library/ms174420.aspx
http://msdn.microsoft.com/en-us/library/ms187928.aspx
http://msdn.microsoft.com/en-us/library/ms177532.aspx
To get hh:mm format from today's date:
select getdate()
select convert(varchar(5),getdate(),108)
To get hh:mm format from any datetime column in a table data:
select date_time_column_name from table_name where column_name = 'any column data name'
select convert(varchar(5),date_time_column_name,108) from table_name
where column_name = 'any column data name'
select creationdate from employee where Name = 'Satya'
select convert(varchar(5),creationdate,108) from employee
where Name = 'Satya'
SELECT CAST(CAST(GETDATE() AS Time(0)) AS VARCHAR(5))