This question already has answers here:
Closed 6 years ago.
I am trying to convert the current time (system time) in to milliseconds ...is there any inbuilt functions i can use to solve this easily .
For example i have used the following code to get the time and display it.
System.Diagnostics.Debug.WriteLine("Time "+ String.Format("{0:mm:ss.fff}",DateTime.Now));
The output i get is
Time 36:50.527
as in minutes:seconds.milliseconds
I need to convert the time i got now in to Milliseconds.
You need a TimeSpan
representing the time since your epoch. In our case, this is day 0. To get this, just subtract day 0 (DateTime.Min
) from DateTime.Now
.
var ms = (DateTime.Now - DateTime.MinValue).TotalMilliseconds;
System.Diagnostics.Debug.WriteLine("Milliseconds since the alleged birth of christ: " + ms);
You didn't specify, but usually when you need the time in milliseconds, it's because you're passing it off to a system that uses Jan 1st 1970 UTC as its epoch. JavaScript, Java, PHP, Python and others use this particular epoch.
In C#, you can get it like this:
DateTime epoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
long ms = (long) (DateTime.UtcNow - epoch).TotalMilliseconds;