Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Save DateTime and completely ignore timezone

Tags:

c#

.net

Maybe the answer is so obvious, I'm not seeing it, but I have a question that I'll risk asking anyway.

I want to allow users of a .NET Web application to enter a date/time, store it in an Oracle database, and no matter which timezone they are in, it always displays as the raw, original version as typed in by the user. So if one user in California enters 2PM and another in Maryland enters 2PM, they would both show as 2PM to a user in Japan. Two types of clients are possible, a web user and a windows client user (connected via web service).

Think of it like I want to completely break all timezone smarts that most applications worry about.

I don't want to save as a string though. I want a datetime that I can add/remove hours and minutes from.

Edit:

This was basically the exact problem I was having.

like image 290
Rake36 Avatar asked Dec 22 '22 09:12

Rake36


1 Answers

You should always store DateTime in UTC format (universal). When you display it you can choose which ever timezone you wish, in your case this can be fixed for all users, rather than based on location.

// when recording date time
DateTime utcDateTime = DateTime.UtcNow;

// parse DateTime back out from string
DateTime utcDateTime = DateTime.SpecifyKind(DateTime.Parse(dateStr),
                                            DateTimeKind.Utc);

// localized DateTime
DateTime localDate = utcDateTime.ToLocalTime();

// fixed DateTime based on timezone
string timeZoneKey = "New Zealand Standard Time";
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneKey);
DateTime nzlocalDate = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, timeZone);

This takes into account things like day-light savings which can trip you up if start saving localized dates.

like image 83
TheCodeKing Avatar answered Dec 24 '22 00:12

TheCodeKing