C#自特定日期起的秒数
在C#3.0中,如何获得自2010年1月1日以来的秒数?您可以减去2个日期时间实例并获得时间跨度:C#自特定日期起的秒数,c#,datetime,date-range,C#,Datetime,Date Range,在C#3.0中,如何获得自2010年1月1日以来的秒数?您可以减去2个日期时间实例并获得时间跨度: DateTime date = new DateTime(2010,1,1); TimeSpan diff = DateTime.Now - date; double seconds = diff.TotalSeconds; 是这样的: TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01); MessageBox.Show(t
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
是这样的:
TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
MessageBox.Show(test.TotalSeconds.ToString());
对于一个班轮乐趣:
MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
.TotalSeconds.ToString());
只是为了避免时区问题
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
这实际上是一个你正在使用谁的2010年1月1日,以及你是否希望考虑夏令时的问题
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
与夏令时的差异:105.15:44:09.7003571
没有夏令时的差异:105.14:44:09.7003571
UTC差异:105.20:44:09.7003571
要获取秒数,请使用TimeSpan对象的属性。@Psytronic然后
MessageBox.Show((DateTime.Now-new DateTime(2010,01,01)).TotalSeconds.ToString()代码>应该获得各种投票。ViewData[“计数器乘数”]=(DateTime.Now-new DateTime(2010,01,01)).TotalSeconds.ToString();WinS假设您尚未处于UTC/GMT,这会导致时区问题。您还需要将2010年1月1日转换为UTC(newdatetime(2010,1,1).ToUniversalTime()
)。更大的问题是你可能需要担心夏令时。
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
Difference with Daylight Savings: 105.15:44:09.7003571
Difference without Daylight Savings: 105.14:44:09.7003571
UTC Difference: 105.20:44:09.7003571