I want to convert a DATETIME from a column to a UNIX TIMESTAMP. But the thing is that those dates are in a distant future, such as 2066-09-01... You can try those simple queries:
SELECT UNIX_TIMESTAMP( '2016-09-03 09:00:00' ) returns 1472886000 -> GOOD
SELECT UNIX_TIMESTAMP( '2036-09-03 09:00:00' ) returns 2104038000 -> GOOD
SELECT UNIX_TIMESTAMP( '2066-09-03 09:00:00' ) returns 0 -> BAD! WHY??
Any idea? Any workaround ?
From Unixtimestamp.com:
What happens on January 19, 2038?
On this date the Unix Time Stamp will cease to work due to a 32-bit overflow. Before this moment millions of applications will need to either adopt a new convention for time stamps or be migrated to 64-bit systems which will buy the time stamp a "bit" more time.
Sounds like your rdbms is suffering from the Y2038 problem: https://en.m.wikipedia.org/wiki/Year_2038_problem
Is this MySQL? They have a bug about this: https://dev.mysql.com/worklog/task/?id=1872
Suggest handling this outside SQL if possible. PHP's strtotime() and similar functions in other languages can play nice with MySQL's ISO date format.
Related
Hi there please help me .
I'm using this code
Weekstart = DATEDD(Wk, DATEDIFF(d,0,CONVERT(DATE, GETDATE(),103)) / 7,0)
This above query is given me the output in this format '2022-02-07 00:00:00.000' however I want the date in this format '07-Feb-22'
Some things to avoid:
Shorthand like Wk and d - this isn't code golf
Magic dates like 0 - again, not code golf
Style 103 doesn't belong here at all, that is when you are taking a string in a regional format (which you also should avoid), not when converting a datetime to a date
Lots more things to avoid here: Dating Responsibly
I would do it this way. Use a base date that you know falls on the same weekday that you consider the start of the week:
DECLARE #base date = '20180101';
SELECT Weekstart = REPLACE(CONVERT(char(9),
DATEADD(WEEK, DATEDIFF(DAY, #base, GETDATE())/7, #base), 6),' ','-');
The only magic / shorthand in here is the style number, 6, which is a very specific way to coerce a date/time into a specific format (discover them all here). Some will suggest the built-in FORMAT() function, which matches capability in other languages like C#, but I suggest avoiding it. Not only is it not available in flavors of SQL Server that don't support CLR or x64 (like Azure SQL Edge), the overhead is substantial.
I didn't find any simple answer to this while I was looking around, so I thought I'd put it up here in case anyone was having the same problem as me with what should have been a trivial issue.
I was using ReDash analytics with Google's BigQuery and had turned on Standard SQL in the datasource settings. For the purposes of my query, I needed to convert a timestamp - unix time in milliseconds, as a string - to a Date format so that I could use the DATE_DIFF method.
As an example... "1494865480000" to "2017-05-15"
The difficulty was that casting and conversion was excessively strict and there seemed no adequate way to make it parse. See my answer down below!
(Though let me know if some SQL sensei knows a more eloquent way!)
In Standard SQL use TIMESTAMP_MICROS function together with EXTRACT(DATE FROM <timestamp>):
SELECT EXTRACT(DATE FROM TIMESTAMP_MILLIS(1494865480000))
A simpler way with TIMESTAMP_MILLIS():
#standardSQL
SELECT DATE(TIMESTAMP_MILLIS(CAST("1494865480000" AS INT64)))
2017-05-15
After much trial and error, this was my solution:
DATE_ADD( DATE'1970-01-01', INTERVAL CAST( ( CAST( epochTimestamp AS INT64 ) / 86400000 ) AS INT64 ) DAY ) AS convertedDate
That is, I took the string, cast it to an integer, divided it by the number of milliseconds in a day, then used a DATE_ADD method, and added the result to the start of Epoch time, and calculated the resulting day.
I hope this saves another junior some time!
Use UTC_USEC_TO_TIMESTAMP():
select UTC_USEC_TO_TIMESTAMP(postedon * 1000)
You can then extract the date using date():
select DATE(UTC_USEC_TO_TIMESTAMP(postedon * 1000))
This doesn't require knowing the internal format of Unix timestamps.
My date is not in standard form. This is how it is: 07/15/2013 06:53:05 and is stored as string in the database.
How can I query it to order it by date.
This query is not working.
SELECT jobno, ondate FROM Reports ORDER BY DATE(ondate)
When I run this query it orders it alphabetically and not date wise.
As written here, SQLite doesn't have a date type, so you can do this:
SELECT jobno, ondate
FROM Reports
ORDER BY substr(ondate,7)||substr(ondate,1,2)||substr(ondate,4,2)
sql fiddle demo
This is why this format is not a recommend date/time storage mechanism in SQLite.
You can use strftime to covert the data into something that can be well-ordered (note that we just have to specify the American-ish format string), e.g.
SELECT jobno, ondate FROM Reports
ORDER BY strftime('%m/%d/%Y %H:%M:%S', ondate)
However, this approach (as well as the approach in the other answer) will not be able to use indices and performance on large data may suffer!
From SQLite Datatypes: 1.2 Date and Time Datatype the advice is:
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
I recommend using ISO 8601 as it's still human-readable, is well-understood (and culture neutral), can encode the TZ (just be consistent!), and can be indexed well.
I need to get a SQL query to output the date from a datetime field in the format Mmm dd yyyy hh:mm AM/PM. The best aproach I've been able to come up with so far is:
SELECT Left(
Convert(
nvarchar(30),
SWITCHOFFSET(
CAST(datetime1 as datetimeoffset),
'-05:00'
),
0
),
LEN(
Convert(
nvarchar(30),
SWITCHOFFSET(
CAST(datetime1 as datetimeoffset),
'-05:00'
)
)
)-11
)
However, a) it's ugly! I feel like this should be simpler than that; and b) I think going to have to change my query when Daylight savings time comes back.
The source data is a sharepoint calendar, so I can't simply change the datatype to datetimeoffset.
Any ideas?
Thanks,
Steve
As a general principal you should not be using SQL to format data into something presentable for the front end. You should be getting a DateTime type back, and using code on the format to change it. What if a future requirement comes in to support DD/MM/YYY? You'll need a separate query. It's better to let the front end format it for that.
With that in mind, store 2 pieces of data in the database. 1) DateTime as a UTC value 2) The current user's timezone (not offset)
The reason you store timezone and not offset is because of all the rule involved with DST. For example, the days that DST starts end aren't fixed in stone. They are set for a country each year, but that schedule can change, and that's a bad reason to need to update your code (unless you're writing a timezone library.)
Then once you have these two pieces of data, you retrieve the date, and the timezone, and construct a new object in the server that allows you to convert the time in the DB to the local time.
Am I missing something, or is it simply:
Convert(nvarchar(30), DATEADD(Hour, -5, datetime1), 100)
That should add -5 hours to datetime1, then convert it into the format you were specifying.
I do agree that you should try to deal with timezones instead of offsets whenever possible.
According to the documentation I've found from AR Systems on BMC Remedy, timestamps in an MSSQL Server environment (we're using SQL Server 2005 here) are stored as an int datatype in UNIX timestamp format.
I cannot for the life of me get custom SQL in Business Objects Web Intelligence to let me convert this timestamp into mm/dd/yyyy format, which I need to be able to group records by a date (without the timestamp, obviously). Anything I try to do involving math or datatype conversion throws an "invalid type" error. I can't convert the field to an int, varchar, datetime, or anything else. The only function that works is DATEADD, which still returns the full timestamp.
How can I get this converted? I'm going nuts here!
to convert GMT/UTC/Zulu to Local time Zone(EDT/New York):
DATEADD(hour,-5,DATEADD(s,Last_Modified_Date,'1/1/1970 00:00:00'))
Example of use to display Remedy work info entries (Transact-SQL):
SELECT Work_Log_ID, DATEADD(hour, +12, DATEADD(s, Last_Modified_Date, '1/1/1970 00:00:00')) as Last_Modified_Date , Description, Detailed_Description, Infrastructure_change_ID, Number_of_Attachments
FROM dbo.CHG_WorkLog
WHERE Infrastructure_Change_ID = 'CRQ001261'
ORDER BY Work_Log_ID desc
Why doesn't this work?
DECLARE #timestamp INT
SELECT #timestamp = DATEDIFF(s,'1/1/1970 00:00:00',GETDATE())
SELECT DATEADD(s,#timestamp,'1/1/1970 00:00:00')
Substitute the #Timestamp with the value from your table.
You may need to multiply the int timestamp by 1000. The AR System stores the date as the number of 'seconds' where as most other languages store the unix timestamp as milliseconds (and as a long data type)
Hope that helps!
Go to
user tool -> Tools -> Options -> Locale tab -> Date/Time Style -> Custom Format -> mm/dd/yyyy