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.
Related
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
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");
}
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…)
I'm trying to calculate a timesheet i'm working on within a JS onChange event, the following works but it wont work past midnight, for example 23:00 - 01:00 returns 22 instead of 2 or rather 2.00 as I'd like it to report to 2 decimal places.
$startm = date_create({mS}); //create a php datetime object
$finishm = date_create({mF});
$t_diff = date_diff($startm, $finishm); //calculate the difference
{mT} = $t_diff->h + round($t_diff->i/60,2) + {mOt} + {mOt2} /24; //add everything up
The form has the following fields
Start Tme = mS - 24hr time
Finish Time = mF - 24hr time
Overtime = mOt - int
Overtime 2 = mOt2 - int
Total = mT - int
You can just add a check if $startm is past noon and $finishm is NOT past noon, $total -= 12. This of course won't work for shifts that last more than 24 hours, but that doesn't seem to be an acceptance criteria for your code.
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'.