0

I have an MVC3 application that is recently published to a web server. This server has a different timezone than mine, and that means DateTime.Now on this server is different from my own. That also means that all times shown on the website is shown wrong for me.

The user base for this application all live in the same time zone, so I am looking for a method to override the servers time zone, and use my own timezone instead.

I really don't want to just add or deduct hours based on the difference, since that will get messed up when daylight saving occurs.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • Maybe it helps: http://stackoverflow.com/questions/1320048/how-to-do-timezones-in-asp-net-mvc. Probably you will need to define the users time zone somehow. – Samich Sep 30 '11 at 07:17
  • 1
    [No need to deduct anything manually.](http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx) The date and time stuff in .NET has been DST aware since at least 3.5 SP1. – bzlm Sep 30 '11 at 07:21
  • Yes, but the problem is to get this offcet. And as I know it's possible only on client side: http://stackoverflow.com/questions/1572905/get-client-machine-timezone-in-asp-net-mvc – Samich Sep 30 '11 at 07:22

1 Answers1

2

You could use something like this to convert the current UTC date/time to your local time:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);

Just change the Id passed into TimeZoneInfo.FindSystemTimeZoneById to be your local time zone identifier.

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
James
  • 80,725
  • 18
  • 167
  • 237
  • Not exactly what I hoped for, but some tricking around with TimeZoneInfo gave me a solution I can live with at least. I'll mark your as accepted since it got me on the right track :) – Øyvind Bråthen Sep 30 '11 at 10:43
  • I think ideally you want a solution where you could just change the TimeZone of the current thread which means you wouldn't have to do a conversion everytime you are dealing with dates. However, .NET doesn't support this. – James Sep 30 '11 at 10:57
  • James - Yes, that is what I really wanted. No I have to convert the time all places I want to display it to the user. – Øyvind Bråthen Sep 30 '11 at 13:06
  • My suggestion would be to either have an extension method on the `DateTime` object or create a static class which does the conversion for you as it keeps everything in the one place. – James Sep 30 '11 at 13:13
  • James - That was what I ended up doing. Extension method was the least amount of pain. – Øyvind Bråthen Oct 01 '11 at 09:05