I have an ASP.NET MVC app that is not converting dates values properly. I reside in one time zone. My users resides in another. At this time, assume I have the following string:
var date = "7/1/2014 4:00:00 AM +00:00";
I am converting this string to a DateTime using the following:
DateTime temp;
if (DateTime.TryParse(date, out temp))
{
temp = temp.ToShortDateString();
WriteToLog(temp);
}
When temp is written to the log file, I see it being written as 6/30/2014. What would possibly cause this? I'm expecting 7/1/2014. It works on my machine. However, it is not working on my users machine.
The answer is timezones. You're parsing a specific point in time (4:00 AM, GMT). This is the same point in time as say 10:00 PM CST the day before.
If you keep it in UTC:
var s = temp.ToUniversalTime().ToShortDateString();
You'll get the requested output.
string date = "7/1/2014 4:00:00 AM +00:00";
DateTime temp;
if (DateTime.TryParse(date, CultureInfo.InstalledUICulture,
DateTimeStyles.AdjustToUniversal, out temp))
{
string result = temp.ToShortDateString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With