Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting dates in C#

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.

like image 582
user70192 Avatar asked Dec 05 '25 21:12

user70192


2 Answers

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.

like image 66
Kyle W Avatar answered Dec 08 '25 12:12

Kyle W


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());
}
like image 24
Dreamweaver Avatar answered Dec 08 '25 12:12

Dreamweaver



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!