What is the equivalent of Java's System.currentTimeMillis() in C#?
What is the equivalent of Java's System.currentTimeMillis() in C#?
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;
}
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 :)
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);
}
}
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.
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