14

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

craigmoliver
  • 6,499
  • 12
  • 49
  • 90

6 Answers6

30

Goes like this:

  TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
  MessageBox.Show(test.TotalSeconds.ToString());

For one liner fun:

 MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
     .TotalSeconds.ToString());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MadBoy
  • 10,824
  • 24
  • 95
  • 156
17

You can substract 2 DateTime instances and get a TimeSpan:

DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
driis
  • 161,458
  • 45
  • 265
  • 341
2

Just to avoid timezone issues

 TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));

 int timestamp  = (int) t.TotalSeconds;

 Console.WriteLine (timestamp);
Hanseh
  • 717
  • 4
  • 17
  • 4
    Assuming you're not already in UTC/GMT, this causes time zone issues. You need to convert 1/1/2010 to UTC as well (`new DateTime(2010, 1, 1).ToUniversalTime()`). The bigger issue you may need to worry about it daylight savings. – Austin Salonen Apr 16 '10 at 20:17
2

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.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
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;
}
Sam
  • 7,252
  • 16
  • 46
  • 65
Justin
  • 10,667
  • 15
  • 58
  • 79
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());
Sam
  • 7,252
  • 16
  • 46
  • 65
Nayan
  • 3,092
  • 25
  • 34