10

I am writing an application in C#, and I would love to know how you can get the number of seconds in each month. For example, today, February the 3th, I would love to have:

January: 2678400
February: 264000

Basically, I would love to know how many seconds in the past months and how many seconds in the current month at the current time (how many seconds so far).

Any code snippets would be appreciated....

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Job
  • 101
  • 1
  • 1
  • 3

3 Answers3

23

Subtracting one date from another will always give you a TimeSpan of the difference:

TimeSpan diff = (new DateTime(2011, 02, 10) - new DateTime(2011, 02, 01));

Console.WriteLine(diff.TotalSeconds);
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
16

You can subtract two dates from each other and get the total seconds between them.

DateTime start = new DateTime(2011, 02, 03);
DateTime end = DateTime.Now;
var seconds = (start - end).TotalSeconds; 

The result of subtracting two dates from each other is a TimeSpan.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
9

You can get the TotalSeconds property from a TimeSpan:

TimeSpan ts = DateTime.Now.Subtract(new DateTime(2011,2,1));
Console.Write(ts.TotalSeconds);

will give you the seconds so far this month.

Mark Avenius
  • 13,679
  • 6
  • 42
  • 50