简体   繁体   中英

DST in JavaScript

How can I check in JS file whether current Date is in DST or not?

In C# there is the below code available to check this. Can anyone suggest similar code in JS?

var timezone = TimeZone.CurrentTimeZone
var tzById = TimeZoneInfo.FindSystemTimeZoneById(timezone.StandardName);
var localDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzById);

Let's start with the C# code you provided. You have a bug. FindSystemTimeZoneById expects a value from the Id property of a TimeZoneInfo object. You are looking it up by the StandardName of a TimeZone object, which might work, but only for some time zones, and only on English language systems. The Id is not localized, but the names are. Really, you should never use TimeZone . Just use TimeZoneInfo . If you want the local TimeZoneInfo , then just use TimeZoneInfo.Local .

But really, you have just written an elaborate version of DateTime.Now . Your code doesn't do anything other than that. The equivalent JavaScript is simply new Date() .

So, you asked how to determine if the current date is in daylight saving time or not. I will also assume you meant for the local time zone. In C# it is simply DateTime.Now.IsDaylightSavingTime . In JavaScript, it is a bit trickier.

There are a few different ways, but this one is pretty easy. See this site for detailed explanation.

Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

Now you can check new Date().dst and get a simple true/false result.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM