javascript wrong date / days calculation - javascript

I need to calculate the number of nights between 2 dates, it works but it's very odd.
If I pick dates like 22,06,2015 and 22,07,2015 it shows me 31 nights, which is wrong since June has only 30 days.
if I pick dates like 01,07,2015 and 31,07,2015 it shows me 30 nights, which is correct.
if I pick dates like 01,07,2015 and 1,08,2015 it shows me 31 nights etc.
if I pick dates like 30,09,2015 and 30,10,2015 it shows me 31.041666666666668 nights which is odd and incorrect.
Hope you can help me with this one. Here's the code:
var date11 = $("#in").val();
var date22 = $("#out").val();
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date111 = date11.split('-');
date222 = date22.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date111[2], date111[1], date111[0]);
date2 = new Date(date222[2], date222[1], date222[0]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
Thanks a million!

You aren't subtracting 1 from the calendar month number:
date1 = new Date(date111[2], date111[1] - 1, date111[0]);
--------^^^^
Months are zero indexed. you should probably also round the result as if you cross a daylight saving boundary, the time value won't be an even number of days, it will be out by 1 hour (unless you cross two boundaries…)

Related

How do i get remaining seconds of future date in javascript

So i have an API, which gives me date format like this 11/21/2022 19:00:00 what i need to do is i have to schedule notification for this datetime, but the problem is i am using react-native/expo which accepts the scheduling time in seconds.
How do i convert this datetime to seconds, i mean if today's date is 11/15/2022 12:00:00 and the date on which the notification should be scheduled is 11/16/2022 12:00:00 which means the future date in 1 day ahead of todays date, and 1 day is equal to 86400 seconds, which means i have to trigger notification after 86400 seconds. So how do i get the remaining seconds of the upcoming date?
Use .getTime()
function Date.prototype.getTime() returns number of milliseconds since start of epoch (1/1/1970)
get the number of milliseconds and divide it 1000 to seconds
subtract (round) and you have the difference
according to Date.parse() is only ISO 8601 format of ECMA262 string supported, so use:
new Date("2022-11-16T12:00:00Z")
or new Date(2022,10,16,12)
rather not n̶e̶w̶ ̶D̶a̶t̶e̶(̶"̶1̶1̶/̶2̶1̶/̶2̶0̶2̶2̶ ̶1̶9̶:̶0̶0̶:̶0̶0̶"̶)̶ that can lead to unexpected behaviour
const secondsInTheFuture = new Date("2022-11-16T12:00:00Z").getTime() / 1000;
const secondsNow = new Date().getTime() / 1000;
const difference = Math.round(secondsInTheFuture - secondsNow);
console.log({ secondsInTheFuture, secondsNow, difference });
You can get the epoch time in js with the function + new Date, if you are passing any date value, to new Date(dateValue), please make sure to stringify.
+ new Date
To get the diff b/w these two dates in seconds,
const initialDate = '11/15/2022 12:00:00'
const futureDate = '11/16/2022 12:00:00'
const diffInSeconds = (+ new Date(futureDate) - + new Date(initialDate)) / 1000
ps: epoch time is in milliseconds, hence dividing by 1000.
Solved using dayjs package
const dayjs = require("dayjs")
const d1 = dayjs("2022-11-15 13:00")
const d2 = dayjs("2022-11-16 12:00")
const res = d1.diff(d2) / 1000 // ÷ by 1000 to get output in seconds
console.log(res)

Javascript Countdown timer does not work

I came across this codepen https://codepen.io/donovanh/pen/JWdyEm, and I was trying to apply it to an older countdown timer I did because this one seemed better.. If I set the countdown date to today then it still says there is 30 days left.
Here is the code where it calculates the difference between dates.
function daysBetween( date1, date2 ) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
console.log("Days to end of April = " +
daysBetween(new Date(), new Date("2018-04-30")));
I cannot figure out where the extra days are coming from, any help would be appreciated, thanks
I think that your problem comes from giving wrong month number as argument to Date.UTC. According to docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC, month is a 0-11 number. If you would like to call function for todays date, you have to call it like new Date(2018, 3, 10, 12, 15).
Months start from 0 and go to 11.
The end of April is Date("2018-03-30"), not Date("2018-04-30") that is why you get extra 30 or 31 days

How can we subtract time using moment,js?

I have time1 = '09:00 AM' and time2 = '06:30 PM'.
How can i subtract these two using moment.js, such a way that i get the result = 9hrs 30mins.
I searched through the internet but couldn't find an apt solution.
Any suggestions are much appreciated.
I suggest programming your own custom function that converts the time to 24 hrs, adding 12 hours if PM, 0 if AM. It then converts the times in to minutes, subtracts the two times, and converts them back into HH:MM AM/PM.
(Pseudocode (reads a bit like javascript))
//ap = am or pm; 0 for am, 1 for pm
define "subtractTimes" (time1, time1ap, time2, time2ap):
//gets the length of time1 and time2
set "time1Length" to (length(time1))
set "time2Length" to (length(time2))
//adds 12 hours if pm, converted to minutes
set "time1InMinutes" to (time1ap * (12 * 60))
set "time2InMinutes" to (time2ap * (12 * 60))
//gets minutes from time1 and time2
//You'd have to program your own function "getLetters"
//Unless there's one that I'm unaware of.
set "time1MM" to (getLetters(time1,(time1Length-1),time1Length))
set "time2MM" to (getLetters(time2,(time2Length-1),time2Length))
//this script makes sure the times are the proper length.
if "time1Length" = (4)
set "time1" to (("0")join(time1)
if "time2Length" = (4)
set "time2" to (("0")join(time2)
//gets hours from time1 and time 2
set "time1HH" to (getLetters(time1,(time1Length-4),time1Length-3))
set "time2HH" to (getLetters(time2,(time2Length-4),time2Length-3))
//puts it all together
set "time1InMinutes" to (time1InMinutes+(time1HH*60)+time1MM)
set "time2InMinutes" to (time2InMinutes+(time2HH*60)+time2MM)
set "newTimeInMinutes" to ((time1InMinutes)-(time2InMinutes))
//converts it to HH:MM AM/PM
set "newTime" to (floor(newTimeInMinutes/60))
set newTimeInMinutes" to (newTimeInMinutes-(newTime*60))
if "newTime" > (12):
set "newTime" to (newTime-12)
set "ap" to (AM)
else
set "ap" to (PM)
set "newTime" to ((newTime)join(":")join(newTimeInMinutes))
set "newTime" to ((newTime)join(" ")join(ap)
//end
This should work. If you have any questions, feel free to ask.

How to subtract 2 times with moment.js, then subtract some minutes

I need to subtract 2 times with moment.js (get the difference), and then with that result, subtract some additional minutes (simple int). It's for calculating timesheets. A few examples:
Example #1:
Start time: 10:00 AM (represented in js as "10:00")
End time: 2:00 PM (represented in js as "14:00")
Lunch: 30 minutes ("30")
Expected result: "3:30" (10am - 2pm is 4 hours, minus 30 minutes for lunch = 3hrs 30 mins -- and I need it output as "3:30")
Example #2:
Start time: 6:15 AM (represented in js as "6:15")
End time: 4:45 PM (represented in js as "16:45")
Lunch: 0 minutes ("0")
Expected result: "10:30"
I know moment.js can do this but I'm struggling to get expected results. I've been trying this:
function getTimeInterval(startTime, endTime){
return moment(moment(startTime,"hh:mm").diff(moment(endTime,"hh:mm"))).format("hh:mm");
}
The formatting seems right, but I'm getting incorrect values. For example, the result returned for my example #2 is "6:30" instead of "10:30" And then how do I subtract off int minutes for lunch?
Any help is much appreciated.
// parse time using 24-hour clock and use UTC to prevent DST issues
var start = moment.utc(startTime, "HH:mm");
var end = moment.utc(endTime, "HH:mm");
// account for crossing over to midnight the next day
if (end.isBefore(start)) end.add(1, 'day');
// calculate the duration
var d = moment.duration(end.diff(start));
// subtract the lunch break
d.subtract(30, 'minutes');
// format a string result
var s = moment.utc(+d).format('H:mm');
Pay close attention to the casing of the formats. You were using hh which is for a 12-hour clock.
See also: Get the time difference between two datetimes
You can use the diff method to calculate the difference between two dates and the subtract method to subtract time. In your case:
function getTimeInterval(startTime, endTime, lunchTime){
var start = moment(startTime, "HH:mm");
var end = moment(endTime, "HH:mm");
var minutes = end.diff(start, 'minutes');
var interval = moment().hour(0).minute(minutes);
interval.subtract(lunchTime, 'minutes');
return interval.format("HH:mm");
}

Convert any String time to seconds

I'm trying to convert 15:00 (15minutes) to seconds though I get 54,000 when I use this below.
I'm trying to convert 15minutes to seconds.
S = '15:00';
D = "1/1/1 "
s = ( new Date(D+S) - new Date(D) )/1000
alert(s);
Though when I do the math, it's 60 x 15 = 900. How do I get 900, since the time is a random string.
Well if your format will always be "mm:ss" you could dome string parsing and do the math manually, of course this would need to be adjusted depending on the input format.
S = '15:25';
var times = S.split(":");
var minutes = times[0];
var seconds = times[1];
seconds = parseInt(seconds, 10) + (parseInt(minutes, 10) * 60);
alert(seconds);​
Note in the example I explicitly added 25 seconds just as demonstration.
http://jsfiddle.net/Jg4gB/
The time string '15:00' in JavaScript refers to the time of day 1500hr, or 3:00 p.m. American-style. That's 15 hours after midnight. That explains why you got 54,000 seconds.
If you wanted to express 15 minutes using your method of manipulating date strings, try '00:15:00'.

Categories