How do i get the correct getTimezoneOffset() - javascript

I need to be able to get the correct timezoneOffset by using javascript, if a user has disabled "Automatically adjust time clock for Daylights saving time" on his or her computer.
For example if i turn on automatically adjust DST i get -420 in june, and -480 in January for Pacific Time zone.
However if i disable Automatically adjust DST i get -480 for both January and June.
Is there any way to correct this behavior so that i get the expected DST even if automatically adjust DST time is checked off?

This is a function I've used a little while back (source), hope this helps.
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
//go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
//To ignore daylight saving time look for the lowest offset.
//Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
To detect DST without using getTimezoneOffset use this:
var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
temp = june1.toGMTString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
dst = "0"; // daylight savings time is NOT observed
} else {
dst = "1"; // daylight savings time is observed
}

Related

compare two dates by day in javascript

I'm trying to compare two dates by day in javascript. Comparing dates is fine, but I want just compare them by day and ignore the time of day. Is this possible without relying on a library like momentjs?
Here is a snippet that compares dates without time:
var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);
if(d >= today){
alert(d is greater than or equal to current date);
}
And here is a function that will give you the exact difference between two days:
function daysBetween(first, second) {
// Copy date parts of the timestamps, discarding the time parts.
var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());
// Do the math.
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
return Math.floor(days);
}

Why Daylight Saving is not detected by Javascript in my code?

I have tried below code to detect if Daylight Saving is observed or not, but although it's on, it always says it's not observed.
var myDate = new Date();
document.write(myDate.getTimezoneOffset());
var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toUTCString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
temp = june1.toUTCString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
dst = "0"; // daylight savings time is NOT observed
} else {
dst = "1"; // daylight savings time is observed
}
It's currently returning me "not oberserved", no matter which way I am using. (Can't add all methods here as it will be too long question)
Hence, I just want to confirm:
Does that require any settings in my machine?
Is there any specific country you have to be in to get this observed?
That code seems really complicated for what it needs to do. Here's a simple function that makes the same assumption you do (that DST is not in effect on Jan 1st of the year) and detects whether DST is in effect for the given Date instance:
function isDST(dt) {
// Northern or southern hemisphere?
// NOTE: Assumes that Jan 1st (southern hemisphere) or July 1st (northern hemisphere) will be DST
// This may be a "good enough" assumption, but if not, you'll need to download timezone information
const jan1 = new Date(dt.getFullYear(), 0, 1);
const jul1 = new Date(dt.getFullYear(), 6, 1);
const ref = jan1.getTimezoneOffset() < jul1.getTimezoneOffset() ? jul1 : jan1;
return dt.getTimezoneOffset() !== ref.getTimezoneOffset();
}
console.log(isDST(new Date(2018, 6, 1))); // true (if July 1st is DST in your timezone)
console.log(isDST(new Date(2018, 1, 1))); // false (if Feb 1st is not DST in your timezone)
It takes advantage of the fact that getTimezoneOffset includes the DST offset if DST is in effect.
Of course, if a location should change the timezone it's in permanently between the two dates, it would give a false positive, but that's a relatively rare occurrence.
The OP has been modified since my original answer so that it no longer applies. T.J. has alternative code, but so as not to waste an answer, here's a similar function that:
Gets the timezone offset for 1 Jan and 1 Jul for the related year
Assumes DST is in force and returns true if either:
the place observes DST as for the southern hemisphere DST (i.e. Jan offset is less than Jul offset, noting that javascript offsets are the opposite sense of ISO and all other commonly used systems) and the offset is the same as for January
the place observes DST as for the northern hemisphere DST (same caveat as above) and the offset is the same as for July
For any other case (jan offset equals jul offset so no DST at all, or date offset is as for non–DST offset) the date must not be in DST
function inDST(inDate) {
var inOffset = inDate.getTimezoneOffset();
var janOffset = new Date(inDate.getFullYear(), 0, 1).getTimezoneOffset();
var julOffset = new Date(inDate.getFullYear(), 6, 1).getTimezoneOffset();
return (janOffset < julOffset && janOffset == inOffset) ||
(janOffset > julOffset && julOffset == inOffset);
}
// Just a helper for testing
function fDate(d) {
var z = n => (n < 10 ? '0' : '') + n;
return `${z(d.getDate())}-${d.toLocaleString(undefined, {month:'short'})}-${d.getFullYear()}`;
}
// Tests
[new Date(2018, 1, 2), // 2 Feb 2018
new Date(2018, 5, 30)] // 30 Jun 2018
.forEach(d =>
console.log(`${fDate(d)}: ${inDST(d)}`)
);

How to calculate milliseconds since beginning of the day?

I've specified a specific time on a certain day. Now I wish to calculate the milliseconds from the beginning of that specific day to the set time of that day? I was hoping to do that with below code, but instead it shows nothing? What am I doing wrong?
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01").getTime();
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
I specify the countDownDate. Then I mark the beginning of that countDownDate into the variable countDownStart. Next I calculate the time passed since 00:00 of January 10 to 00:01 of January 10 by subtracting countDownStart from countDownDate. But no result is shown...
Your code has only one issue, and that is that you've assigned the result of .getTime() to countDownDate, which will be a number.
That's why JavaScript cannot call getFullYear, or any other function on that number, because those will be invalid calls.
To correct that, just remove the .getTime(), and it will work fine.
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
<div id="result">
<div>
Your logic is fine here. The only issue is this line here:
var countDownDate = new Date("January 10, 2018 00:01").getTime();
Since you used .getTime() the variable countDownDate is no longer a date. As such in the following statementcountDownDate.getFullYear() and forward isn't going to work. Simply remove .getTime() and it will work as expected:
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
console.log(countDownTime)

NetSuite - excluding weekends from date calculation

My scheduled script sets a field to store an accrued late fee charge for each day an invoice is overdue. I am comparing the current system time against due date to work out the number of days overdue. However, I didn't take into consideration to exclude the weekend. How can I use my existing code to do this?
var current_date = nlapiStringToDate(nlapiDateToString(new Date()));
var dd = invoice.getFieldValue('duedate');
var due_date = nlapiStringToDate(dd);
if (due_date < current_date) {
//Other Calculations
var days_overdue = DateOverdue(current_date, due_date);
}
function DateOverdue(current_date, due_date) {
var time_difference = Math.abs(due_date.getTime() - current_date.getTime());
var no_days_overdue_by = Math.ceil(time_difference / (1000 * 3600 * 24));
return no_days_overdue_by;
}
The following works. Note the extra dates are to clear issues from comparing time stamps without hours, minutes and seconds. Not strictly needed for the current_date given how you are generating it but it makes a more general function.
NOTE: I don't believe you should be able to compare dates with d1 < d2.
function daysOverdue(currentDate, dueDate){
var days = 0;
var due = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate(), 0, 0, 0);
var fromTS = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0).getTime();
if(due.getTime() >= fromTS) return 0; // not overdue
while(due.getTime() < fromTS){
if(due.getDay() !== 0 && due.getDay() != 6) days++;
due.setDate(due.getDate() + 1);
}
return days;
}

flipclock countdown to specific date in specific timezone without reset

I am trying to create countdown to a specific date using flipclock without the timer resetting or people in different time-zones seeing different numbers. For example, I want to countdown to Feb 20, 12:00am MST.
My problem is that the clock resets when the browser is refreshed after it reaches 0, the time shows negative numbers. If people viewing this clock with the current configuration, it is counting down to Feb 20, 12am in their timezone.
I've started with the countdown to New Years compiled clock and set my date, but not sure how else to address the timezone and reset issues.
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
var clock;
$(document).ready(function() {
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
Part solving timezone issue (a bit ugly):
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
Part limiting time difference to not less than zero:
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
Since the time you'd like to count down to is a specific time in a specific time zone, then the easiest way is to pre-convert that time to UTC, and count down to that instead.
On Feb 20th 2016, US Mountain Time is at UTC-7, therefore:
2016-02-20 00:00:00 MST == 2016-02-20 07:00:00 UTC
So,
var currentDate = new Date();
var futureDate = Date.UTC(currentDate.getUTCFullYear(), 1, 20, 7, 0, 0);
var diff = (futureDate - currentDate.getTime()) / 1000;
I'll let someone else answer WRT the specifics of FlipClock and your reset issue - though you might consider asking it in a separate question. (Try to ask only one question at a time in the future.)

Categories

Resources