4

I have one application which need server to process the client request.

In this application time is very important.

Whenever client request anything, i would like to save the time of the request.

Problem is, my server is in US and client is in australia.

How can i change server time to client time and save it on database.

This should be accurate even during day light saving.

How can i achieve this

Ok i have save time in database as UTC.

On client side i have this code,

 DateTime dt = booking.CreateDateTime.Value;
 var localTime = TimeZone.CurrentTimeZone.ToLocalTime(dt);

When i print that localTime, it is 7 hour faster then local time.

How can i change that time to local time?

Amrit Sharma
  • 1,906
  • 8
  • 45
  • 75

4 Answers4

4

The guideline I know states that times should always be saved as UTC in the database, never local. This way you avoid many local time difference pitfalls (including daylight savings).

When you need the local time, retrieve it as UTC from the database and convert it. You can use the DateTime struct to help you out with this:

var utcNow = DateTime.UtcNow;
SaveToDB(utcNow);
var utcFromDb = RetrieveTimeFromDb();
var localTime = DateTime.ToLocalTime(utcFromDb);
Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198
  • 3
    Yes, always deal in UTC and only convert to some timezone and dst for display. Also, if it wasn't obvious, the time should be generated in server. – Esailija Nov 03 '12 at 16:33
0

It's typically best practice to store dates in UTC, and then translate to a locale when necessary.

var date = DateTime.UtcNow();
var tzi = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
var offset = tzi.GetUtcOffset(date);
lukiffer
  • 11,025
  • 8
  • 46
  • 70
0

Maybe take a look at the TimeZoneInfo class?

If that doesn't satisfy your needs, there's Noda Time.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
0

Agreed that the time should be stored in UTC. The problem will comein when converting to the client's local time (not the server's). To convert to the client's local time, you will need to know the client's time zone information and store this with the UTC time in the db.

Then with both pieces of information you should be able use the above methods to convert to the client's local time.

Kevin
  • 552
  • 2
  • 4
  • I store the time in UTC in database. And retrieved that time and convert it to the local time. But the converted time is 7 hours faster then local time. – Amrit Sharma Nov 03 '12 at 17:13