C# 如何在 Visual Studio 中将当前时间转换为毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19315668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert the Current Time to milliseconds in Visual Studio?
提问by Ranga Praveen
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
时间 36:50.527
as in minutes:seconds.milliseconds
以分钟为单位:seconds.milliseconds
I need to convert the time i got now in to Milliseconds.
我需要将我现在进入的时间转换为毫秒。
采纳答案by Gusdor
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
.
您需要TimeSpan
代表自您的时代以来的时间。在我们的例子中,这是第 0 天。要得到这个,只需从 中减去第 0 天 ( DateTime.Min
) DateTime.Now
。
var ms = (DateTime.Now - DateTime.MinValue).TotalMilliseconds;
System.Diagnostics.Debug.WriteLine("Milliseconds since the alleged birth of christ: " + ms);
回答by Matt Johnson-Pint
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.
您没有指定,但通常当您需要以毫秒为单位的时间时,这是因为您将其传递给使用 1970 年 1 月 1 日 UTC 作为其纪元的系统。JavaScript、Java、PHP、Python 和其他人使用这个特定的时代。
In C#, you can get it like this:
在 C# 中,你可以这样得到:
DateTime epoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
long ms = (long) (DateTime.UtcNow - epoch).TotalMilliseconds;