Answer to Question 1
... does
DateTimeOffset.UtcNow
always returns the correct UTC date and time, regardless of whether the server is dependent on daylight savings time?
Yes. As long is your clock is set correctly, UtcNow
always refers to the UTC time. The time zone settings of the server will not affect it. The value in your example will always be 4 minutes, regardless of DST.
Answer to Question 2
var offset = new Date().getTimezoneOffset();
Since new Date()
returns the current date and time, this will return you the current offset. You then proceed to apply this current offset to some past value, which may or may not be the correct offset for that specific time. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".
Answer to Question 3
Is the value obtained correct? Is this the right approach to solving this problem?
No. This is not the correct approach. You have a few options:
First Option
- Just pass the UTC value to JavaScript without modification.
- Send it in ISO8601 format, such as
2013-10-18T12:34:56.000Z
. You can get this in .Net easily usingyourDateTime.ToString("o")
.- Be sure the
DateTime
you are starting with has.Kind == DateTimeKind.Utc
, otherwise it won't get theZ
on the end, which is essential. - If you are targeting older browsers that can't parse ISO8601, then you will need a library such as moment.js to parse it for you.
- Be sure the
- Alternatively, you could pass the number of milliseconds since 1/1/1970 UTC as a number and load that into a JavaScript
Date
instead of parsing. - Now you can just display the
Date
object using JavaScript. Let the browser convert it from UTC to the users local time.
Warning, with this approach, some conversions might be incorrect due to the problem I describe here.
Second Option
- Like the first option, pass the UTC timestamp to JavaScript
- Use that to get the offset for that timestamp.
- Pass the offset back to the server in a postback or ajax call.
- Apply the offset on the server
- Output the local time zone
I don't particularly like this option because of the round trip. You might as well calculate it in JavaScript like the first option.
Third Option
- Get the user's time zone. The best way is to ask them for it, usually on a user setting page.
- Use it to convert from the UTC time to their local time completely on the server.
- You can use Windows time zones and the
TimeZoneInfo
class to do the conversions. - Or you can use IANA/Olson time zones and the Noda Time library.
- If you do this, you can optionally use a map-based timezone picker.
- You can take a guess at the user's time zone with jsTimeZoneDetect.
This approach is more accurate, but requires more user interaction.
Also, please in future posts, ask just one question at a time. And please search before you post - I've written most of this in one form or another many times before.