I am working on a web application where date time store in database in UTC. Now when I retrieve the date time to show in UI then I have to convert the date time to the specific time from where the user in using the application.
To convert the time from UTC to specific local time I was doing some demo research. I found two way to convert the time. One is from server side and another is from client side. In server side I am using ASP.NET and in client side I am using JavaScript. But the problem is that the answers are not same.
I am giving the code.
Server side:
Label1.Text = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).ToString();
Client side:
$(document).ready(function () {
var offset = new Date().getTimezoneOffset();
$('#Label1').text(offset / 60);
});
In the case of server side code it is showing 05:30:00 in the label. In the case of client side code it is showing -5.5 in the label.
My question is why this two UTC offset is not same ??
The offsets are formatted differently.
The server-side sample appears to be a Date
-like object. The client-side version appears to be a int
( 330
).
The values in these appear to match, though.
Looking at the specification , your server-side code returns a TimeSpan
object, while your JavaScript does indeed return a integer.
It's simply a formatting thing. If your offset is +5:30 then getTimezoneOffset
will return 330, which is the minutes to add to your local time to get UTC.
If you are passing the time as a value of milliseconds since 1970-01-01T00:00:00Z then you can give that directly to the Date constructor:
var localDate = new Date(timevalue);
To return an equivalent UTC time value, use getTime
:
var UTCTimeValue = localDate.getTime();
Javascript date objects use a UTC time value with the system timezone offset to return local date and time values (eg for getDate , getHours , etc.), or UTC values if UTC methods are called (such as getUTCDate , getUTCHours , etc.).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.