Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime's representation in milliseconds?

I have a SQL-server timestamp that I need to convert into a representation of time in milliseconds since 1970. Can I do this with plain SQL? If not, I've extracted it into a DateTime variable in C#. Is it possible to get a millisec representation of this ?

Thanks,
Teja.

like image 664
Tejaswi Yerukalapudi Avatar asked May 10 '11 20:05

Tejaswi Yerukalapudi


People also ask

How do you write milliseconds in time format?

Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.

How do I print the date in milliseconds?

date +"%T. %6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds. date +"%T. %3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.

How do you represent milliseconds?

A millisecond (from milli- and second; symbol: ms) is one thousandth (0.001 or 10−3 or 1/1000) of a second.

How do you convert ticks to milliseconds?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second.


4 Answers

You're probably trying to convert to a UNIX-like timestamp, which are in UTC:

yourDateTime.ToUniversalTime().Subtract(     new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)     ).TotalMilliseconds 

This also avoids summertime issues, since UTC doesn't have those.

like image 61
Andomar Avatar answered Sep 20 '22 01:09

Andomar


In C#, you can write

(long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds
like image 27
SLaks Avatar answered Sep 24 '22 01:09

SLaks


As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.

DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();

As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.

Here you can learn more about DateTimeOffset.

like image 41
Bob Avatar answered Sep 24 '22 01:09

Bob


There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class

DateTime.UtcNow.ToUnixTimeMs()

like image 42
dmirg Avatar answered Sep 24 '22 01:09

dmirg