在 C# 3.0 中,我如何获得自 2010 年 1 月 1 日以来的秒数?
问问题
20177 次
6 回答
28
像这样:
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());
于 2010-04-16T20:02:51.413 回答
16
您可以减去 2 个 DateTime 实例并获得一个 TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
于 2010-04-16T20:02:21.553 回答
2
只是为了避免时区问题
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
于 2010-04-16T20:05:25.647 回答
2
这实际上取决于您正在使用谁的 2010-Jan-01,以及您是否希望考虑夏令时。
//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 对象的TotalSeconds属性。
于 2010-04-16T20:43:10.600 回答
1
protected void Page_Load(object sender, EventArgs e)
{
SecondsSinceNow(new DateTime(2010, 1, 1, 0, 0, 0));
}
private double SecondsSinceNow(DateTime compareDate)
{
System.TimeSpan timeDifference = DateTime.Now.Subtract(compareDate);
return timeDifference.TotalSeconds;
}
于 2010-04-16T20:06:01.570 回答
0
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());
于 2010-04-16T20:06:30.437 回答