Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

like image 527
Pit Digger Avatar asked Mar 21 '26 16:03

Pit Digger


1 Answers

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.

like image 69
Alex Aza Avatar answered Mar 23 '26 07:03

Alex Aza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!