mashta gidi
mashta gidi

Reputation: 857

C# show client local time instead of UTC time from database

I am using asp.net c#. When the user perform an action I am saving the action datetime in the db using UTC time. Now when its time to present the actions, I am sending json to client with the datetime from the db. Now the problem is that it is being present in utc time and that is really confusing to the user. What are the optional solutions to my issue? should they be client based or server based?

Upvotes: 1

Views: 3594

Answers (3)

Mike Gledhill
Mike Gledhill

Reputation: 29201

I answered this exact question here:

How to get current user timezone in c#

Basically, in your database, you should store the time in UTC. Then, you need to get your JavaScript to call your WCF web service, and pass it the user's local timezone.

Your service can add this timezone-offset to the UTC time, and return back the date-times in the user's local time.

Upvotes: 1

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30265

I think that the most correct way is to keep sending the data to the client the same way you do now (in UTC), then you will be able to convert it to Local or any other timezone as you wish during the presentation, but keep using the UTC in calculations if any.

There are multiple questions on how to do that in javascript, e.g. here

Append 'UTC' to the string before converting it to a date in javascript:

var date = new Date('6/29/2011 4:52:48 PM UTC');

date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

P.S. Not sure you can do various time-zones in js, but at least it should work with the local one

Upvotes: 2

Cee McSharpface
Cee McSharpface

Reputation: 8725

Convert the UTC time to local time based on the time zone of the client. If that is done server-side or client-side, is a matter of design, logic/presentation layer separation.

If you choose to do it server side, you will need the information of the client's local time zone available. Given that, you can write:

TimeZoneInfo.ConvertTimeFromUtc(utcdate, clients_timezoneinfo)

Beyond the c# part, there is good coverage on time zone offsets in client browsers, for example get client time zone from browser

Upvotes: 0

Related Questions