-1

My web site is in .net mvc. I have saved dates from client side using jQuery calendar into database MS SQL. Also I have saved dates using DateTime.Now. The problem is that the application is hosted on server which is in America, but my client is in Pakistan. They want time according to Pakistani time.

I tried to use TimeZoneInfo class but I am unable to use it as class library, or as DLL. How can I use a static sealed class and access its methods? Secondly I have used culture ur-PKR in web.config; it allows me to add dates in format dd/MM/yyyy which is working fine (according to PK style). Now after using culture style ur-PK, should I use Timezoneinfo class or not?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

Firstly, you should separate DateTime formatting from time zones. They're completely separate problems.

For most scenarios (but not all), you should save values in your database in UTC, and convert them to the appropriate time zone when you need to display them to the client - that's also the point at which you should convert them to strings. (You should be storing the values in a DateTime field or something similar in your database - not varchar).

To convert from a UTC value to the Pakistan time zone, you just obtain the TimeZoneInfo with TimeZoneInfo.FindSystemTimeZoneById and then call TimeZoneInfo.ConvertTimeFromUtc. If you only need the same time zone everywhere, you can call FindSystemTimeZoneById just once and keep a reference to it.

// Ignore the "standard time" part - it really is both standard and daylight where
// necessary.
private static readonly TimeZoneInfo PakistanZone =
    TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time");

...

DateTime utc = ...; // DateTime.UtcNow, or a stored value
DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, PakistanZone);

You might also want to consider using my Noda Time library, which makes it easier to keep track of which is local, which is an instant in time etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I am unable to use TimeZoneInfo class !! I tried to add as reference but it doesn't add !! what do u suggest ... secondly should i save date in utc.now ?? – Wajahat Qureshi Mar 09 '15 at 19:57
  • @WajahatQureshi: You don't add a *reference* to a class. You just add a reference to an assembly, and a using directive for the namespace. But as it's in the `mscorlib` assembly and the `System` namespace, you probably don't need to do anything. And yes, you *probably* want to store timestamps in UTC, as I said in my post. – Jon Skeet Mar 09 '15 at 20:00