MrMAG
MrMAG

Reputation: 1264

Datetime.now as TimeSpan value?

I need the current Datetime minus myDate1 in seconds.

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;

TimeSpan myDateResult = new TimeSpan();

myDateResult = myDate2 - myDate1;

.
.
I tried different ways to calculate but to no effect.

TimeSpan mySpan = new TimeSpan(myDate2.Day, myDate2.Hour, myDate2.Minute, myDate2.Second);

.
The way it's calculated doesn't matter, the output should just be the difference these to values in seconds.

Upvotes: 29

Views: 104370

Answers (7)

YC Chiranjeevi
YC Chiranjeevi

Reputation: 611

Code:

TimeSpan myDateResult = DateTime.Now.TimeOfDay;

Upvotes: 51

Prerna
Prerna

Reputation: 1

TimeSpan myDateResult;

myDateResult = DateTime.Now.Subtract(new DateTime(1970,1,9,0,0,00));
myDateResult.TotalSeconds.ToString();

Upvotes: 0

Chaturvedi Dewashish
Chaturvedi Dewashish

Reputation: 1469

You can use Subtract method:

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan ts = myDate2.Subtract(myDate1);
MessageBox.Show(ts.TotalSeconds.ToString());

Upvotes: 1

Guffa
Guffa

Reputation: 700910

Your code is correct. You have the time difference as a TimeSpan value, so you only need to use the TotalSeconds property to get it as seconds:

DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;

TimeSpan myDateResult;

myDateResult = myDate2 - myDate1;

double seconds = myDateResult.TotalSeconds;

Upvotes: 31

Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13602

you need to get .TotalSeconds property of your timespan :

DateTime myDate1 = new DateTime(2012, 8, 13, 0, 05, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate2 - myDate1;
MessageBox.Show(myDateResult.TotalSeconds.ToString());

Upvotes: 2

Arcturus
Arcturus

Reputation: 27065

How about

myDateResult.TotalSeconds

http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds

Upvotes: 5

Adriaan Stander
Adriaan Stander

Reputation: 166606

Have you tried something like

DateTime.Now.Subtract(new DateTime(1970, 1, 9, 0, 0, 00)).TotalSeconds

DateTime.Subtract Method (DateTime)

TimeSpan.TotalSeconds Property

Upvotes: 7

Related Questions