C# DateTime.AddMinutes increments months at midnight

So last night I was writing an application that would process trunk logs from Connect Assist’s ShoreTel phone system which would allow the raw per-call data to be turned in to trunk usage stats (but that’s another story).

I came across an issue where using the DateTime.AddMinutes() function at midnight of the changing value was incrementing months instead of days i.e. instead of changing 07/02/2012 23:59:00 to 07/03/2012 00:00:00 it was changing it to 08/02/2012 00:00:00.

Now, maybe due to tiredness, it took me a while to work out the solution (a while being about 30-40 mins) and there was nothing already listed in Google as an answer so I just thought I’d share it with others in case anyone else comes across the issue. I think it’s pretty clear that the issue is down to the DateTime interpreting the date format incorrectly (despite my expectation that it would recognise the US format – it may be that this is a UK format issue only) but I couldn’t quite work out how to fix this (there doesn’t seem to be a property of DateTime that you can change, the DateTime constructor was useless to me as I was using DateTime.Parse and DateTime.Parse did not have a method of formatting) but then I found DateTime.ParseExact(String, String, IFormatProvider).

I have used this as follows:

DateTime dateTime = DateTime.ParseExact("07/02/2012 11:59:00 PM", "MM/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Now when call dateTime.AddMinutes(1) it will return a DateTime of value 07/03/2012 00:00:00.

I hope that helps someone!

About Stephen Pickett

Stephen Pickett is a programmer, IT strategist and architect, project manager and business analyst, Oracle Service Cloud and telephony expert, information security specialist, all-round geek. He is currently Technical Director at Connect Assist, a social business that helps charities and public services improve quality, efficiency and customer engagement through the provision of helpline services and CRM systems.

Stephen is based in south Wales and attended Cardiff University to study Computer Science, in which he achieved a 2:1 grading. He has previously worked for Think Consulting Solutions, a leading voice on not-for-profit fundraising, Fujitsu Services and Sony Manufacturing UK as a software developer.

Stephen is the developer of ThinkTwit, a WordPress plugin that allows you to display multiple Twitter feeds within a blog.

1 thought on “C# DateTime.AddMinutes increments months at midnight

  1. // It’s realy work

    DateTime tdateTime2 = tdateTime1.AddMinutes(item.RepeaterInterval).AddTicks(-1).ToLocalTime ();

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.