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!