C# seconds since specific date

前端 未结 6 1694
醉话见心
醉话见心 2020-12-11 15:48

In C# 3.0, how do I get the seconds since 1/1/2010?

6条回答
  •  鱼传尺愫
    2020-12-11 16:28

    It's really a matter of whose 2010-Jan-01 you're using and whether or not you wish to account for daylight savings.

    //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
    

    To get the seconds, use the TotalSeconds property off the TimeSpan object.

提交回复
热议问题