zxprince
zxprince

Reputation: 387

In MVC3 (C#) Convert GMT DateTime to user local time and local time to GMT DateTime

I am new in MVC3 and C# also. I am going to create a test blog site by MVC3 with C#. Where user can write post so i need to store user post date-time and wanna show that date-time every other user by there own local time. Everybody thought it better to store date-time in GMT for this case.

I don't know how to get user local date-time and convert it into GMT and store. I don't know how to convert and show that stored date-time in each user local date-time.

please help me. please

Upvotes: 2

Views: 2104

Answers (1)

danludwig
danludwig

Reputation: 47375

I will have to respectfully disagree with COLD TOLD only on one point. If you use DateTime.Now, you will get the date & time of the machine that is running your app server. While this is okay, when storing it, you would need to also store the timezone along with it. Otherwise, when converting, you would not know what timezone you are converting from. If you hard-coded it into your app, then you moved it to a data center server in a different timezone, you would have to change that app setting.

On the other hand, if you always store the date & time using DateTime.UtcNow then you only need to store 1 value in your database. When it comes time to convert it to a timezone locale, you don't have to hit the database to find out which timezone the info was originally computed against -- it is always UTC / GMT.

var destinationTimeZone = TimeZoneInfo.FindSystemTimeZoneById(
    "US Mountain Standard Time"); 

utc = DateTime.UtcNow;
mst = TimeZoneInfo.ConvertTimeFromUtc(utcTime, destinationTimeZone);

Console.WriteLine("UTC: " + utc.ToString("yyyy-MM-dd HH-mm-ss"));
Console.WriteLine("MST: " + mst.ToString("yyyy-MM-dd HH-mm-ss"));

Upvotes: 2

Related Questions