Amrit Sharma
Amrit Sharma

Reputation: 1916

Time conversion to client time c#

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?

Upvotes: 4

Views: 2497

Answers (4)

Kevin
Kevin

Reputation: 562

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.

Upvotes: 0

Ohad Schneider
Ohad Schneider

Reputation: 38142

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);

Upvotes: 4

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61982

Maybe take a look at the TimeZoneInfo class?

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

Upvotes: 0

lukiffer
lukiffer

Reputation: 11313

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);

Upvotes: 0

Related Questions