How to get the number of seconds between two dates in javascript? - javascript

Im trying to get the number of seconds between two dates in javascript.
Questions here and here suggest that a simple subtract operation should do the trick and other answers suggest that you use either the .getTime() or .valueOf() attributes.
But Despite all that when I subtract the two dates, Which are apart by 5 seconds I get the value 1551181475795 which is way too large to be correct.
Here is my code:
var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");
// Find the distance between now and the count down date
var distance = Math.abs(now - countDownDate / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id='demo'>
As you can see both times are only apart by 5 seconds but the value that separates them makes no sense.
Thanks in Advance!

It's a matter of operations order, you're dividing the countDownDate by 1000 before doing the subtraction (you're calculating now - countDownDate / 1000 however, you should calculate (now - countDownDate) / 1000, subtraction first):
var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");
// Find the distance between now and the count down date
var distance = Math.abs((now - countDownDate) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>

As you had researched you can simply reduce the newer date from the older one which returns the milliseconds between the two dates.
Dividing that with 1000 gives you the seconds.
let start = new Date("Mar 16, 2019 16:33:25")
let end = new Date("Mar 16, 2019 16:33:30");
let secondsBetween = (end - start) / 1000;
console.log("without value of:", secondsBetween, "seconds")
start = new Date("Mar 16, 2019 16:33:25").valueOf()
end = new Date("Mar 16, 2019 16:33:30").valueOf()
secondsBetween = (end - start) / 1000;
console.log("using value of:",(end - start) / 1000, "seconds")

Related

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;
}

Percentage between two dates compared to today

I am creating a UI which will contain Milestones and I will be using a progress bar to show this.
I am trying to come up with the percentage we are from the date the milestone is set to be completed vs today's date.
For example if I have a milestone called "Live to Site" that is set to happen on December 1, 2015, and I put the milestone in on Jan 1st, I want to determine the percentage we are from the start date to the end date.
Fiddle: http://jsfiddle.net/zz4c16fx/2/
var start = new Date(2015,0,1), // Jan 1, 2015 - The date we put this milestone in
end = new Date(2015,7,24), // June 24, 2015 - The date the milestone is due
today = new Date(), // April 23, 2015
p = Math.round(100-((end - start) * 100 ) / today) + '%';
// Update the progress bar
$('.bar').css( "width", p ).after().append(p);
That was my attempt at it but either my math is wrong or I am thinking about this incorrectly. The number its returning is 99%. I feel that number should be lower seeing how we have 1.5 months left from today.
My end result is to show a progress bar that show how close we are to the completion date given the start, end and today's date.
Try this:
var start = new Date(2015, 0, 1), // Jan 1, 2015
end = new Date(2015, 7, 24), // August 24, 2015
today = new Date(), // April 23, 2015
p = Math.round(((today - start) / (end - start)) * 100) + '%';
// Update the progress bar
$('.bar').css("width", p).after().append(p);
Demo: http://jsfiddle.net/zz4c16fx/6/
Try this, convert the end and start date to unit timestamp values.
// Convert to unix values timestamp values
var startDate = start.getTime();
var endDate = end.getTime();
var todayDate = today.getTime();
// Get the total possible timestamp value
var total = endDate - startDate;
// Get the current value
var current = todayDate - startDate;
// Get the percentage
var percentage = (current / total) * 100;
alert(percentage);
JsFiddle http://jsfiddle.net/x3snbz2w/2/
To get the percentage of days elapsed thus far between one date and another, you need to calculate the time between start and end, then calculate the time between start and today. Then divide the second number by the first:
var start = new Date(2015,0,1),
end = new Date(2015,7,24),
today = new Date();
var timeBetweenStartAndEnd = (end - start);
var timeBetweenStartAndToday = (today - start);
var p = Math.round(timeBetweenStartAndToday / timeBetweenStartAndEnd * 100);
console.log("Percentage of days elapsed thus far: " + p);

Date difference larger than intended

I am learning to use Date object in Javascript. Tried to calculate difference between now and some set date, but it returns a much larger value than inteded. The codepen is here, I can't seem to figure what I did wrong... Help?
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
var now = new Date(); //Now, whenever this code runs
var diff = Math.round((setdate.getTime() - now.getTime())/1000); //Difference in seconds
function NiceTimer(delta) { //Decompose the difference in seconds into date units.
this.days = Math.floor(delta/ 86400);
delta -= this.days*86400; //Subtract the value once it has been "extracted".
this.hours = Math.floor(delta/ 3600);
delta -= this.hours*3600;
this.minutes = Math.floor(delta/ 60);
delta -= this.minutes*60;
this.seconds = delta;
this.printString = function() {
return "The event starts in "+this.days+" days, "+this.hours+" hours, "+this.minutes+" minutes and "+this.seconds+" seconds"; //Output a readable countdown string
}
}
var timer = new NiceTimer(diff);
var el = document.getElementById("timer");
el.innerHTML = timer.printString();
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
Change the four to a three, months start at index zero.
var setdate = new Date(2014, 3, 27, 14,30);
Date # MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.

How do i get the correct getTimezoneOffset()

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
}

Categories

Resources