Pit Digger
Pit Digger

Reputation: 9780

.NET Date Add Days

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.

Upvotes: 3

Views: 11128

Answers (4)

SILAMBARASAN
SILAMBARASAN

Reputation: 31

Example:

txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/

double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/

DateTime  tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/

txt_total.Text = tom.ToString("MM/dd/yy")

Upvotes: 3

Alex Aza
Alex Aza

Reputation: 78447

Try using DateTimeOffset.Parse. Then use AddDays or AddHours.

It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.

var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");

if you don't like the way "O" formats, you can use this:

var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")

This will 100% match to your format.

Upvotes: 9

Michael Christensen
Michael Christensen

Reputation: 1786

That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.

Upvotes: 0

Related Questions