在C#3.0中,如何获得自2010年1月1日以来的秒数?
答案 0 :(得分:25)
这样:
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());
答案 1 :(得分:15)
您可以减去2个DateTime实例并获取TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
答案 2 :(得分:2)
只是为了避免时区问题
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
答案 3 :(得分:2)
这真的是你在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));
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
要获取秒数,请使用TimeSpan对象的TotalSeconds属性。
答案 4 :(得分: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;
}
答案 5 :(得分: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());