What is the equivalent of Java's System.currentTimeMillis()
in C#?
views:
2457answers:
5
A:
The framework doesn't include the old seconds (or milliseconds) since 1970. The closest you get is DateTime.Ticks which is the number of 100-nanoseconds since january 1st 0001.
Cristian Libardo
2008-11-14 14:38:38
Would (DateTime.Ticks/10000000)-(the number of seconds between 0001 and 1970) give an accurate answer?
Liam
2009-04-23 10:54:00
+11
A:
An alternative:
private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long CurrentTimeMillis()
{
return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
Jon Skeet
2008-11-14 14:40:49
+1
A:
the System.currentTimeMillis()
in java returns the current time in milliseconds from 1/1/1970
c# that would be
public static double GetCurrentMilli()
{
DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0,0,DateTimeKind.Utc);
TimeSpan javaSpan = DateTime.UtcNow - Jan1970;
return javaSpan.TotalMilliseconds;
}
edit: made it utc as suggested :)
Hath
2008-11-14 14:44:32
DateTime.Now uses the local time, not UTC. I don't know exactly what happens when you subtract an unknown kind of DateTime from a local one, but it's best to set both of them to UTC :)
Jon Skeet
2008-11-14 15:35:34
+1
A:
Here is a simple way to approximate the Unix timestamp.
Using UTC is closer to the unix concept, and you need to covert from double
to long
.
TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
long millis = (long)ts.TotalMilliseconds;
Console.WriteLine("millis={0}", millis);
prints:
millis=1226674125796
gimel
2008-11-14 14:52:25
+4
A:
We could also get a little fancy and do it as an extension method, so that it hangs off the DateTime class:
public static class DateTimeExtensions
{
private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long currentTimeMillis(this DateTime d)
{
return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);
}
}
Joel Coehoorn
2008-11-14 15:08:41
Lol! I do that sometimes: have to switch back and forth between the two a lot, but normally it's in the IDE so I have instant feedback on it.
Joel Coehoorn
2008-11-14 17:46:00