Groups | Blog | Home
all groups > c# > may 2007 >

c# : add timespan to datetime


Lars Schouw
5/21/2007 11:12:53 PM
I would like to to add a time span "1Y 2M 3W 20D" entered as a string
to a date time how do I do that?

Lars
Jon Skeet [C# MVP]
5/22/2007 12:00:00 AM
[quoted text, click to view]

Well, you'll need to parse the string yourself into a TimeSpan. After
that, however, it's easy:

TimeSpan x = ...;
DateTime y = ...;

DateTime total = y+x;

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Lars Schouw
5/22/2007 3:01:48 AM
I just read the documentaion quickly does TimeSpan also work with
years, months, weeks?
I can find days.
Lars

[quoted text, click to view]

Jon Skeet [C# MVP]
5/22/2007 3:17:27 AM
[quoted text, click to view]

Months and years vary in length, so you'll need to work out exactly
what you mean. If you want to add 1 year to Jan 1st and always get Jan
1st, you may want to look at adding each field individually rather
than using TimeSpan: DateTime has AddYears and AddMonths methods.
(Note that these return new DateTime values - DateTime itself is
immutable.)

Weeks is just a matter of multiplying by 7 and treating as days.

Jon
AddThis Social Bookmark Button