We were trying to determine why the start date field in a tool we use was stored as a bigint. I thought it may be ticks.
To figure this out we tried to do the following. It did not get our answer, but it was a very cool use of the binary data type.
DECLARE @date datetime = '1/22/2013'
,@ticksPerDay BIGINT = 864000000000declare @date2 datetime2 = @datedeclare @dateBinary binary(9) = cast(reverse(cast(@date2 as binary(9))) as binary(9))declare @days bigint = cast(substring(@dateBinary, 1, 3) as bigint)declare @time bigint = cast(substring(@dateBinary, 4, 5) as bigint)select @date as [DateTime], @date2 as [DateTime2], @days * @ticksPerDay + @time as [Ticks]To figure this out we tried to do the following. It did not get our answer, but it was a very cool use of the binary data type.
DECLARE @date datetime = '1/22/2013'
Detailed reference.
http://stackoverflow.com/questions/7386634/convert-sql-server-datetime-object-to-bigint-net-ticks
Turned out the value was a json formatted date, which is defined as number of milliseconds in Universal Coordinated Time (UTC) since midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. This is based on the face that javascript does not have a datetime datatype, so you can pass the time as a big int (which is what we had) or a string that is formatted like a date. The below test transform targets the date
DateTime2 = '1/1/1970',@TargetDate DateTime2
--change this date for your transformation,@JsonDate BIGINT = 628318530718
,@Milli INT,@Seconds BIGINT
SET @Milli = RIGHT(@JsonDate,3)SET @Seconds = LEFT(@JsonDate,LEN(@JsonDate)-3)SELECT @EpochDate, @JsonDate, @Milli, @Seconds SET @TargetDate = dateadd(ms, @Milli,dateadd(second,@Seconds,@EpochDate))IF ((MONTH(@TargetDate) >= 3 AND DAY(@TargetDate) >= 11 AND HOUR(@TargetDate)AND
(
MONTH(@TargetDate) <= 11 AND DAY(@TargetDate) <= 2))SELECT DATEADD(HOUR,-8, @TargetDate)ELSE SELECT DATEADD(HOUR,-7, @TargetDate)