C# 将日期转换为毫秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9724246/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:34:42  来源:igfitidea点击:

Convert Date to Milliseconds

c#visual-studio-2010highcharts

提问by Linger

I am working with Visual Studio 2010, MVC 3 and C#. I am creating some highcharts and need to have the x-axis be a date. I am pulling the dates from a database and adding them to and array that will then be passed to highcharts. I think highcharts requires the dates to be in millisecond format. Ho do I go about converting a DateTime of '12/20/2011 5:10:13 PM" for example to milliseconds?

我正在使用 Visual Studio 2010、MVC 3 和 C#。我正在创建一些 highcharts 并且需要将 x 轴设为日期。我从数据库中提取日期并将它们添加到数组中,然后将其传递给 highcharts。我认为 highcharts 要求日期为毫秒格式。例如,我如何将“12/20/2011 5:10:13 PM”的 DateTime 转换为毫秒?

采纳答案by Matt Burland

Once you figure out what you want to calculate milliseconds from, you can just take one DateTime object from another to get a TimeSpan object. From TimeSpan you can get TotalMilliseconds.

一旦确定了计算毫秒的依据,您就可以从另一个 DateTime 对象中获取一个 TimeSpan 对象。从 TimeSpan 您可以获得 TotalMilliseconds。

In other words, if start and end are DateTime objects, you can do this:

换句话说,如果 start 和 end 是 DateTime 对象,你可以这样做:

double milliseconds = (end - start).TotalMilliseconds;

回答by Serj-Tm

DateTime[] dates = ;

var minDate = dates.Min();

var msDates = dates.Select(date => (date - minDate).TotalMilliseconds).ToArray();

回答by Marek Grzenkowicz

You can use the DateTime.Ticksproperty and convert the value to milliseconds.

您可以使用DateTime.Ticks属性并将值转换为毫秒。

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

此属性的值表示自 0001 年 1 月 1 日午夜 12:00:00 以来经过的 100 纳秒间隔数,它表示 DateTime.MinValue。它不包括可归因于闰秒的滴答数。

一个刻度代表一百纳秒或百万分之一秒。一毫秒有 10,000 个滴答声。

回答by Ifesinachi Bryan

The .Ticksin C# DateTimegives you the value of any time in ticks. You can thereafter convert to milliseconds as shown below:

.TicksC#中DateTime为您提供了在蜱任何时刻的价值。此后您可以转换为毫秒,如下所示:

long dateticks = DateTime.Now.Ticks;
long datemilliseconds = dateticks / TimeSpan.TicksPerMillisecond;