Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DateTime\Timespan with ToString arrggg..

Status
Not open for further replies.

tmcminn

MIS
Jun 17, 2008
12
US
Hello. I have been playing around with a DateTime.Now, then subtracting a Timespan back three days. Works fine. When I try to mix this in with a ToString format for yyyyMMdd, it breaks. I can get any of the two working but never the third. Example:
Code:
DateTime today = DateTime.Now;
TimeSpan ts = new TimeSpan(3, 0, 0, 0);
today.Subtract(ts);
today.ToString("yyyyMMdd");
Console.WriteLine(today);
What am I doing wrong?
 
I am sorry, the above was incorrect code.

Code:
DateTime today = DateTime.Now;
TimeSpan ts = new TimeSpan(3, 0, 0, 0);
today.Subtract(ts);
Console.WriteLine(today.ToString("yyyyMMdd"));

It prints the correct format, but it is for todays date, not three days back.
 
Found the answer
Code:
DateTime today = DateTime.Now;
TimeSpan ts = new TimeSpan(3, 0, 0, 0);         Console.WriteLine(today.Subtract(ts).ToString("yyyyMMdd"));

Now.. can anyone tell me why it worked with this and not with the other code? Logically, it seemed like it should have worked.
 
I cannot answer with absolute authority but my suspicion is that the first code sets the value when you subtract the three days but then resets (or re-initializes?) the today variable when you call the ToString method. In your amended version, you do your subtraction at the same time you call the ToString method and thus it reads it properly. Hopefully that makes sense...

------------------------------------------------------------------------------------------------------------------------
Reason and free inquiry are the only effectual agents against error; they are the natural enemies of error and of error only.

Thomas Jefferson

 
Datetime is an immutable type, just like strings. preforming actions like Subtract() or AddDays() returns a new DateTime object. it does not modify the original.
Code:
DateTime today = DateTime.Now;
TimeSpan ts = new TimeSpan(3, 0, 0, 0);
DateTime three_days_ago = today.Subtract(ts);
Console.WriteLine(three_days_ago);

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Yeah, that's what I was trying to say. jmeckley said it much better. Thanks. [thumbsup]

------------------------------------------------------------------------------------------------------------------------
Reason and free inquiry are the only effectual agents against error; they are the natural enemies of error and of error only.

Thomas Jefferson

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top