remaining minutes and seconds to date are always 59 with moment - javascript

I have two functions in my app, one where I get the instance of the next weekday I choose (get me next mindayfor example), then I have a function which calculates remianing days,hours,minutes and seconds.
Days and hours remaining are calculated correctly but minutes and seconds are always 59
I think this is because when I calculate next instance of monday the resulting timestamp doesn't appear to have a HOUR:MINUTE format, and I want it to be 00:00, so exactly start of the day
nextMonday "2022-03-21T15:11:48.580Z"
LOG Days: 1.999999745370371
LOG Hours: 7
LOG Minutes: 59
LOG Seconds: 59
HOW CAN I ADD HOURS AND MINUTES (00:00) to the moment timestamp I get, I think that would be the problem!
let nextThursday = getNextThursday();
getCountdown();
const getNextDay = () =>
{
const dayINeed = 7; // for monday
const today = moment().isoWeekday();
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
// then just give me this week's instance of that day
return moment().isoWeekday(dayINeed);
} else {
// otherwise, give me *next week's* instance of that same day
return moment().add(1, 'weeks').isoWeekday(dayINeed);
}
};
const getCountdown = (ending) => {
var now = moment();
var end = moment(ending); // another date
var duration = moment.duration(end.diff(now));
//Get Days and subtract from duration
var days = duration.days();
duration.subtract(days, 'days');
//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(hours, 'hours');
//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(minutes, 'minutes');
//Get seconds
var seconds = duration.seconds();
console.log("Days: ", days);
console.log("Hours: ", hours);
console.log("Minutes: ", minutes);
console.log("Seconds: ", seconds);
};

Related

Calculating time elapsed javascript wrong output

I am currently using a script to calculate the time passed in years, months, days etc in Javascript.
$(document).ready(function(){
var birth_date = new Date('March, 25, 2022');
var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){
var current_date = new Date();
var YearDiff = (current_date.getYear() - birth_date.getYear());
var monthDiff = (current_date.getMonth() - birth_date.getMonth());
var daysDiff = (current_date.getDate() - birth_date.getDate());
var hoursDiff = (current_date.getHours() - birth_date.getHours());
var minDiff = (current_date.getMinutes() - birth_date.getMinutes());
var secDiff = (current_date.getSeconds() - birth_date.getSeconds());
ageCount.innerHTML=YearDiff+' Years '+monthDiff+' Months '+daysDiff+' Days '+hoursDiff+
' Hours '+minDiff+' Minutes '+secDiff+' Seconds';
},500);
});`
This seems to output the right months, days and hours when the set date day is lower than the current date (so April 21 when it is now April 22).
0 Years 1 Months 2 Days 8 Hours 14 Minutes 2 Seconds`
When the date day number is higher, it changes it to a certain number of months minus a number of days. Like this (1 month - 4 days, when it should just be 0 months and 27 days).
0 Years 1 Months -4 Days 8 Hours 14 Minutes 38 Seconds
An example of the script is viewable here: https://jsfiddle.net/j2k7n4zp/
Does anyone have a clue what goes wrong or what I need to fix to make it calculate the right amount of days without using minus?
Thanks in advance!
What's going wrong with your code is that assume every part of a later date is higher than every part of an earlier one ... e.g. ... 23 April 2022 to 1 May 2022 - the Date is lower, but the Month is higher - whereas your code naively the Date portion of 1 May is Higher than 23 April just because May is later than April - but that's not how dates work
Here's something I literally whipped up now, see if it helps
const dateDiff = (from, to) => {
// so we don't mutate passed in dates
let start = new Date(from);
let end = new Date(to);
if (+start > +end) {
[start, end] = [end, start];
}
const loop = (prop) => {
const set = `set${prop}`;
const get = `get${prop}`;
let ret = 0;
while (1) {
start[set](start[get]() + 1);
if (start < end) {
ret++;
} else {
start[set](start[get]() -1);
break;
}
}
return ret;
}
const years = loop('FullYear');
const months = loop('Month');
const days = loop('Date');
const hours = loop('Hours');
const minutes = loop('Minutes');
const seconds = loop('Seconds');
const milliseconds = loop('Milliseconds');
return {years, months, days, hours, minutes, seconds, milliseconds}
}
const ageCount = document.getElementById('counter');
setInterval(() => {
const r = dateDiff(new Date(), new Date('2022-03-25'));
ageCount.innerHTML = `${r.years} Years, ${r.months} Months, ${r.days} Days, ${r.hours} Hours, ${r.minutes} Minutes, ${r.seconds} Seconds`;
}, 500);
<div id="counter">
</div>

Issue getting remaining days,hours/minutes.. to date with moment

I have two functions in my app, one where I get the instance of the next weekday I choose (get me next thursday for example), then I have a function which calculates remianing days,hours,minutes and seconds.
So far I can get remaining days, but hours, minutes and seconds show as 0. This is because when the date I get for next thursday doesnt have the required timestamp format:
nextThursday "2022-03-24T15:11:48.580Z"
LOG Days: 5.999999745370371
LOG Hours: 0
LOG Minutes: 0
LOG Seconds: 0
HOW CAN I ADD HOURS AND MINUTES (00:00) to the moment timestamp I get, I think that would be the problem!
let nextThursday = getNextThursday();
getCountdown();
const getNextThursday = () =>
{
const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
// then just give me this week's instance of that day
return moment().isoWeekday(dayINeed);
} else {
// otherwise, give me *next week's* instance of that same day
return moment().add(1, 'weeks').isoWeekday(dayINeed);
}
};
const getCountdown = (ending) =>
{
var now = moment();
var end = moment(ending); // another date
var duration = moment.duration(end.diff(now));
//Get Days and subtract from duration
var days = duration.asDays();
duration.subtract(moment.duration(days,'days'));
//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(moment.duration(hours,'hours'));
//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(moment.duration(minutes,'minutes'));
//Get seconds
var seconds = duration.seconds();
console.log("Days: ",days);
console.log("Hours: ",hours);
console.log("Minutes: ",minutes);
console.log("Seconds: ",seconds);
};
Your problem is you're using asDays() which converts your duration to a decimal number (including hours, minutes, and seconds in decimal part)
And you don't need to call moment.duration(x,'x') in every subtraction
The fix should be
const getCountdown = (ending) => {
var now = moment();
var end = moment(ending); // another date
var duration = moment.duration(end.diff(now));
//Get Days and subtract from duration
var days = duration.days();
duration.subtract(days, 'days');
//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(hours, 'hours');
//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(minutes, 'minutes');
//Get seconds
var seconds = duration.seconds();
console.log("Days: ", days);
console.log("Hours: ", hours);
console.log("Minutes: ", minutes);
console.log("Seconds: ", seconds);
};

javascript calculate the difference between two hours

There is a question that is tricky. Make a function that takes a string argument like 2:00 p.m. or 5:50 a.m.
You must not use momentjs or any other third-party library.
We have three static hours to determine the difference between them and this argument.
7:00 a.m. for breakfast.
12:00 p.m. for lunch.
7:00 p.m. for dinner.
The function should return an array with the first and second elements representing hours and minutes, like below:
eat("2:00 a.m.") // [5, 0];
eat("5:50 p.m.") // [1, 10];
You can start by creating a minutesSinceMidnight() function to get the time since midnight in minutes for a given input string.
We'll then create the timeToEat() function, which will start by finding the next meal time.
Once this is found, we'll get the time to the next meal in minutes, and convert to hours and minutes using
a minutesToHoursAndMinutes() function.
function minutesSinceMidnight(timeStr) {
let rg = /(\d{1,2})\:(\d{1,2})\s+([ap])\.?m/
let [,hour, minute, am] = rg.exec(timeStr);
hour = Number(hour);
if (am === 'a' && hour === 12) hour -= 12;
if (am === 'p' && hour < 12) hour += 12;
return hour * 60 + Number(minute);
}
function minutesToHoursAndMinutes(totalMinutes) {
let hours = Math.floor(totalMinutes / 60);
let minutes = totalMinutes % 60;
return [ hours, minutes]
}
function timeToEat(timeStr) {
let currentTime = minutesSinceMidnight(timeStr);
let mealTimes = ['7:00 a.m', '12:00 p.m.', '7:00 p.m.'].map(minutesSinceMidnight);
let nextMealTime = mealTimes.find(mealTime => mealTime >= currentTime);
// No meal found...
if (nextMealTime === undefined) {
return nextMealTime;
}
let timeToNextMealMinutes = nextMealTime - currentTime;
return minutesToHoursAndMinutes(timeToNextMealMinutes);
}
console.log(timeToEat("2:00 a.m."));
console.log(timeToEat("5:50 p.m."));
console.log(timeToEat("6:30 p.m."));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need some basic functions to convert the time to some common unit that can be compared with some other time. In this case, minutes will do but seconds or milliseconds could also be used.
You also may need to allow for the case where the time is after the last meal, so the time will be the time to the first meal tomorrow.
The following is a simple implementation with some tests. Ideally the data would not be embedded in the timeToNextMeal function so that it's more easily maintained.
// Convert timestamp in h:mm ap format to minutes,
// E.g. 2:30 p.m. is 870 minutes
function timeToMins(time) {
// Get parts of time
let [h, m, ap] = time.split(/\W/);
// Set hours based on value and am/pm
h = h%12 + (/^a/i.test(ap)? 0 : 12);
// Return minutes
return h*60 + m*1;
}
// Convert minutes to array [hours, minutes]
function minsToHM(mins) {
return [mins/60 | 0, mins % 60];
}
function timeToNextMeal(date = new Date()) {
let data = {
'lunch' : '12:00 p.m.',
'breakfast': '7:00 a.m.',
'dinner' : '7:00 p.m.'
};
let minsToMeal = 0;
// Get meal names, ensure sorted by time
let meals = Object.keys(data).sort((a,b) =>
timeToMins(data[a]) - timeToMins(data[b])
);
// Convert time to minutes
let mins = date.getHours() * 60 + date.getMinutes();
// Get next mealtime
let nextMeal = meals.find(meal => timeToMins(data[meal]) > mins);
// If undefined, next meal is first meal tomorrow
if (!nextMeal) {
minsToMeal += 1440 - mins;
mins = 0;
nextMeal = meals[0];
}
// Get minutes to next meal
minsToMeal += timeToMins(data[nextMeal]) - mins;
// Convert minutes to array [H,m]
return minsToHM(minsToMeal);
}
// Examples
[new Date(2022,0,6, 4), // 4 am
new Date(2022,0,6, 5,58), // 5:58 am
new Date(2022,0,6, 9,30), // 9:30 am
new Date(2022,0,6,17,30), // 5:30 pm
new Date(2022,0,6,20, 0), // 8:00 pm
].forEach(d => console.log(
`${d.toLocaleTimeString('en-NZ')} ${timeToNextMeal(d)}`
));

Number of days in the months corresponding to selected dates

I need to find the number of days as days from months chosen between two dates. For example, if I choose date1 as January 1,2021 and date2 as March 1, 2021, then I need to get the total number of days in January, February and March.
Output=
Number of days in january + Number of days in february + Number of days in march = 31+28+31
What I tried:
const getDiff=(selectedDate1,selectedDate2)=>{
console.log('Date check',moment(selectedDate1).daysInMonth(),moment(new Date()).daysInMonth())
if(moment(selectedDate1).daysInMonth() - moment(selectedDate2).daysInMonth() ===0){
return Number(moment(selectedDate1).daysInMonth())
}else{
return Number(moment(selectedDate1).daysInMonth())+Number(moment(selectedDate2).daysInMonth())
}
}
But with this code, i am getting only the sum of days of the selected dates, ie. only Number of days in January + Number of days in March
Using moment.js, you just get the difference between start of the start month and end of the end month in days plus 1 (because the end of month won't include the last day and adding 1 is simpler than going to the start of the following month), e.g.
function wholeMonthDays(d1, d2) {
let diff = moment(d2).endOf('month').diff(moment(d1).startOf('month'),'days') + 1;
return diff;
}
let start = new Date(2021,0,21);
let end = new Date(2021,2,11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Alternatively you can go to the start of the month after end to get the difference:
function wholeMonthDays(d1, d2) {
let start = moment(d1).startOf('month');
let end = moment(d2).startOf('month').add(1, 'month');
let diff = end.diff(start, 'days');
return diff;
}
let start = new Date(2021, 0, 21);
let end = new Date(2021, 2, 11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I've set the dates to during the month to show that it adds the "days in months" rather than just the difference between the two dates.
If you actually want an array of the total days in each month, just set the start to the end of the month, get the date, add one month, set to the end of the month, etc. until you've gone past the end month.
A couple of things:
Remember that Months in Java and JavaScript are (moronically) 0-based. So month 1 is February
To get the number of days in a month you can use a Date object and go to the first of the next month, then substract 1 day, then call getDay.
The time between two dates in milliseconds is
var d1 = ...;
var d2 = ...;
var duration = Math.abs(d2.getTime() - d1.getTime());
You can then divide duration by milliseconds (1000), seconds (60), minutes (60) etc to get the timespan in the unites you'd
The simplest way would be:
// 'lo' and 'hi' could be of type Date or numbers coming from Date.getTime()
const daysBetween = (lo, hi) => {
const oneDayInMilliseconds
= 1000 // one sec has 1000 millis
* 3600 // one hour has 3600 seconds
* 24; // one day has 24 hours
return (hi - lo) / oneDayInMilliseconds;
}

Get the time elapsed between two timestamps and convert it to date [duplicate]

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.
Example:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
//expected result:
"00:39:30"
what I tried:
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");
console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.
The result of moment.duration(now.diff(then)) is a duration with the correct internal values:
days: 0
hours: 0
milliseconds: 0
minutes: 39
months: 0
seconds: 30
years: 0
So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
but i feel that there is something more elegant that I am completely missing.
update
looking closer, in the above example now is:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
and moment(moment.duration(now.diff(then))) is:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(
update 2
well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.
This approach will work ONLY when the total duration is less than 24 hours:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.
This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
It doesn't give you exactly the format you're looking for, but
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1
Worked for me
See more in
http://momentjs.com/docs/#/displaying/difference/
If you want difference of two timestamp into total days,hours and minutes only, not in months and years .
var now = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));
diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:
var days = parseInt(diff.asDays()); //84
var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
hours = hours - days*24; // 23 hours
var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
minutes = minutes - (days*24*60 + hours*60); //20 minutes.
Final result will be : 84 days, 23 hours, 20 minutes.
When you call diff, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.
This should work fine.
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Use this:
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
Instead of
Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
It's better to do
moment.utc(total.asMilliseconds()).format("HH:mm:ss");
This will work for any date in the format YYYY-MM-DD HH:mm:ss
const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();
const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
console.log(duration.asHours());
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
DATE TIME BASED INPUT
var dt1 = new Date("2019-1-8 11:19:16");
var dt2 = new Date("2019-1-8 11:24:16");
var diff =(dt2.getTime() - dt1.getTime()) ;
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var response = {
status : 200,
Hour : hours,
Mins : mins
}
OUTPUT
{
"status": 200,
"Hour": 0,
"Mins": 5
}
The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');
// Getting the difference: hours (h), minutes (m) and seconds (s)
let h = end.diff(start, 'hours');
let m = end.diff(start, 'minutes') - (60 * h);
let s = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);
// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);
console.log(`${hh}:${mm}:${ss}`); // 00:39:30
This will return biggest time period diff like (4 seconds, 2 minutes, 1 hours, 2 days, 3 weeks, 4 months, 5 years).
I use this for notification recent time.
function dateDiff(startDate, endDate) {
let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
let index = 6 - dateMap.filter(e => e == 0).length;
return {
type: arrDate[index] ?? "seconds",
value: dateMap[index] ?? 0
};
}
Example:
dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")
{type: "hours", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")
{type: "days", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")
{type: "seconds", value: 10}
I create a simple function with typescript
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);
function setDiffTimeString(diffDuration: moment.Duration) {
const str = [];
diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
console.log(str.join(', '));
}
// output: 1 day(s), 23 hour(s), 29 minute(s)
for generate javascript https://www.typescriptlang.org/play/index.html
InTime=06:38,Outtime=15:40
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
EPOCH TIME DIFFERENCE USING MOMENTJS:
To Get Difference between two epoch times:
Syntax:
moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()
Difference in Hours:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()
Difference in minutes:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()
Note: You could remove .toFixed() if you need precise values.
Code:
const moment = require('moment')
console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')
Refer working example here:
https://repl.it/repls/MoccasinDearDimension
To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is
const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()
you can change the difference format as you need by just replacing the asMinutes() function
If you want a localized number of days between two dates (startDate, endDate):
var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
nbDaysStr will contain something like '3 days';
See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.
It is very simple with moment
below code will return diffrence in hour from current time:
moment().diff('2021-02-17T14:03:55.811000Z', "h")
const getRemainingTime = (t2) => {
const t1 = new Date().getTime();
let ts = (t1-t2.getTime()) / 1000;
var d = Math.floor(ts / (3600*24));
var h = Math.floor(ts % (3600*24) / 3600);
var m = Math.floor(ts % 3600 / 60);
var s = Math.floor(ts % 60);
console.log(d, h, m, s)
}

Categories

Resources