How to Convert the Current Time to milliseconds in

2020-07-27 18:55发布

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.

2条回答
Lonely孤独者°
2楼-- · 2020-07-27 19:05

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);
查看更多
Rolldiameter
3楼-- · 2020-07-27 19:07

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;
查看更多
登录 后发表回答