Converting time to client time C #

I have one application that needs a server to process a client request.

In this application, time is very important.

Whenever a client requests something, I would like to save the request time.

The problem is that my server is in the USA and the client is in Australia.

How can I change server time to client time and store it in the database.

This should be accurate even in daylight.

How can i achieve this

Ok, I save the time in the database as UTC.

On the client side, I have this code,

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

When I print this localTime, it is 7 hours faster than local time.

How can I change this time to local time?

+4
source share
4 answers

The manual that I know says that the time should always be stored as UTC in the database, and not locally. This way you avoid many local time errors (including daylight saving time).

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

 var utcNow = DateTime.UtcNow; SaveToDB(utcNow); var utcFromDb = RetrieveTimeFromDb(); var localTime = DateTime.ToLocalTime(utcFromDb); 
+4
source

It is generally recommended that you store dates in UTC, and then translate them to a local if necessary.

 var date = DateTime.UtcNow(); var tzi = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time"); var offset = tzi.GetUtcOffset(date); 
0
source

Maybe look at the TimeZoneInfo class ?

If this does not meet your needs, Noda Time .

0
source

It is agreed that the time should be stored in UTC. The problem will occur when converting to the local time of the client (and not on the server). To convert to local time of the client, you will need to find out information about the client’s time zone and save it with UTC time in db.

Then, using both pieces of information, you can use the above methods to convert to the local time of the client.

0
source

Source: https://habr.com/ru/post/1443836/


All Articles