Consider the following query (in MSSQL 2008):
SELECT dateModified FROM SomeTable;
This returns floats in javascript format (milliseconds since 1970):
dateModified
============
1301598290687
1071003581343
1311951478593
How can I convert this to a datetime2 right in the select?
Using the formula from #Mikeal Eriksson's answer here.
I would convert the float to a bigint and then create the datetime:
select
DATEADD(MILLISECOND,
cast(dateModified as bigint) % 1000,
DATEADD(SECOND, cast(dateModified as bigint) / 1000, '19700101'))
from sometable
See SQL Fiddle with Demo
Some Oracle example - replace to_date() with eqivalent:
SELECT (1301598290687/60/60/24/1000) as Days
, to_date('01-01-1970','dd-mm-yyyy') as start_date
, to_date('01-01-1970','dd-mm-yyyy')+(1301598290687/60/60/24/1000) as converted_date
FROM dual
/
DAYS START_DATE CONVERTED_DATE
---------------------------------------------------------
15064.7950310995 1/1/1970 3/31/2011 7:04:51 PM
Create dual table:
CREATE TABLE DUAL
(
DUMMY VARCHAR(1)
)
GO
INSERT INTO DUAL (DUMMY)
VALUES ('X')
GO
Related
I am trying to convert milliseconds to date in SQL Server for a date after 01/01/2040.
I tried this, but I'm getting an error:
Arithmetic overflow error
Code:
CREATE TABLE XYZ
(
[ExpirationDate] float
);
INSERT INTO XYZ ([ExpirationDate])
VALUES
(1301598290687),
(2240542800000),--> this is 01/01/2040
(2144034000000);
SELECT
DATEADD(MILLISECOND,
CAST(ExpirationDate AS bigint) % 1000,
DATEADD(SECOND, CAST(ExpirationDate AS bigint) / 1000, '19700101'))
FROM
XYZ
Also tried
SELECT CAST(ExpirationDate AS DATETIME) FROM XYZ
but that's not working either.
See this https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=4c03a31832364b5a636f47eb66034c19
Looking for Date output like if we pass 2240542800000 ms as value then output should be date 01/01/2040
One method is to split the problem into date and time pieces:
select (DATEADD(DAY,
FLOOR(ExpirationDate / (24*60*60*1000.0) ),
'19700101') +
DATEADD(MILLISECOND, CONVERT(bigint, ExpirationDate) % (24*60*60*1000), 0)
)
from XYZ
How can I convert these kind of date values from varchar to datetime2?
WITH dates AS (
SELECT '6.7.2012' AS dtm
UNION
SELECT '13.2.2012' AS dtm
UNION
SELECT '3.12.2012' AS dtm
UNION
SELECT '20.11.2012' AS dtm
)
SELECT CAST(dtm as datetime2) FROM dates
;
This results in an error:
Msg 241, Level 16, State 1, Line 6
Conversion failed when converting date and/or time from character string.
Use try_convert instead of cast:
WITH dates AS (
SELECT '6.7.2012' AS dtm
UNION
SELECT '13.2.2012' AS dtm
UNION
SELECT '3.12.2012' AS dtm
UNION
SELECT '20.11.2012' AS dtm
)
SELECT TRY_CONVERT(datetime2, dtm, 104) FROM dates
;
Results:
13.02.2012 00:00:00
20.11.2012 00:00:00
03.12.2012 00:00:00
06.07.2012 00:00:00
Note: try_convert was introduced in 2012 version, for earlier versions you need to use convert, risking an exception if the varchar value can't be converted using the specified style.
I'm trying to set a column with a default value or binding of the current date in MSSQL.
I'm currently using GETDATE(), but this gives me the timestamp with the hours, minutes, seconds and milliseconds, I only need the day part (2015-03-05).
Only results I found on the web were these of changing it in the SELECT statement.
If you use it in a date context SQL Server will auto cast it for you
DECLARE #date DATE = GETDATE();
SELECT #date
-- result: 2015-03-05
or you could simply use a cast
SELECT CAST(GETDATE() as DATE)
EDIT:
I'm still not sure if I get what you want, but if you want to do it as a default constraints it works the same way:
create table #table
(
id int,
insertDate date default GETDATE()
)
insert into #table (id) values (1)
select top 1 insertDate from #table
-- result: 2015-03-05
If you want to store only date, excluding time you can use this:
CREATE TABLE #dts(id INT IDENTITY, d_date datetime2 DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
However it will return you zeroes instead of time, as seen here:
id d_date
-------------------------------
1 2015-03-05 00:00:00.0000000
You can remove unwanted characters using LEFT function:
SELECT id, LEFT(d_date, 10) FROM #dts
It will return you:
id d_date
--------------
1 2015-03-05
You could achieve this by using varchar as datatype, but i dont think it would be appropiate solution and it's better to format date in select statement. But if you really need it, then this works:
CREATE TABLE #dts(id INT IDENTITY, d_date VARCHAR(10) DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
Output:
id d_date
--------------
1 2015-03-05
Set your default value on the column to
(CONVERT([date],getdate(),0))
I have used it many times
In other ways to convert DATETIME to DATE (get only date without time) you can use CAST to DATE format.
SELECT CAST(GETDATE() AS DATE)
In your case you can set default value type DATE without CASTing.
CREATE TABLE #TempTable
(
Id INT,
..... ,
CurrentDate DATE DEFAULT GETDATE()
)
The answer to your problem is simple. Change the format of the column that is going to hold the value to a DATE (as opposed to a data type that will hold the time portion, i.e: DATETIME).
Then set the default to GETDATE() and because the destination column is a DATE the time portion will be stripped off for you.
Take this sample code:
CREATE TABLE #temp (id INT, CreatedDate DATE DEFAULT GETDATE())
INSERT INTO #temp ( id)
VALUES ( 1 ),( 2 ),( 3 )
SELECT * FROM #temp
DROP TABLE #temp
Output:
id CreatedDate
1 2015-03-05
2 2015-03-05
3 2015-03-05
You can use CONVERT() to get date in different formats. From http://www.w3schools.com/sql/func_convert.asp :
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
gives you the following results:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
I do have this sample value of "12/01/2013" which is a string.
How can I convert it directly to an SQL statement? The format must be in INT, like this: 20131201
So from "12/01/2013" to 20131201.
See Data Type Formatting functions
select cast(to_char(to_timestamp('12/01/2013', 'MM/DD/YYYY'), 'YYYYMMDD') as int)
this works with SQL Server
SELECT CONVERT(INT, SUBSTRING('12/01/2013',7,4) +
SUBSTRING('12/01/2013',0,3) +
SUBSTRING('12/01/2013',4,2)) AS dateInt
Result
20131201
Tested in MySQL:
SELECT CAST(CONCAT(SUBSTR("12/01/2013",7,4), SUBSTR("12/01/2013",4,2),SUBSTR("12/01/2013",1,2)) AS UNSIGNED INTEGER);
In postgreSQL you have the to_date function which accepts a date string and a format string and returns a date.
So you can:
postgres=# select to_date('12/01/2015', 'mm/dd/yyyy');
to_date
------------
2015-12-01
(1 row)
postgres=# select to_date('12012015', 'mmddyyyy');
to_date
------------
2015-12-01
(1 row)
You can do it using CONVERT and REPLACE function like below.
DECLARE #dateValue date
SET #dateValue = CONVERT(DATETIME,'12/01/2013',102)
SELECT REPLACE ( CONVERT(nvarchar,#dateValue) , '-' , '' )
Rsult will be
20131201
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),':',''))