How to get the total Hours by Subtracting two dates using moment? - javascript

i have to subtract two days and need to get the total hours.
let date1 = moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local().format('MM/DD/YYYY h:mm A');
let date2 = moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local().format('MM/DD/YYYY h:mm A');
let getHours = date1.diff(date2, 'hours')
i need to get the total hours like this way. any different way to resolve this issue ?

Also you can use,
let date1 = moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let date2 = moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var x = moment.duration(date1.diff(date2)).asHours();
from docs

The format function returns a string. So, in your code, date1 and date2 are strings, not momentjs datetime values. Remove the call to format().

After formatted, the date1 does not have diff method which is a string. You can remove the format.
let date1 = moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let date2 = moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let getHours = date1.diff(date2, 'hours');
Or if date1 and date2 are in same timezone:
let date1 = moment();
let date2 = moment(titleDate);
let getHours = date1.diff(date2, 'hours');
Or
date1.diff(date2) / 1000 / 60 / 60;
date1.diff(date2) return milliseconds.

Try this:
var titleDate = new Date(2018, 11, 24, 10, 33, 30);
var originalDate1 = moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var date1 = originalDate1.format('MM/DD/YYYY h:mm A');
var originalDate2 = moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var date2 = originalDate2.format('MM/DD/YYYY h:mm A');
console.log(date1+"\n"+date2);
var duration = moment.duration(originalDate2.diff(originalDate1));//myMoment.diff(now, 'days', true);
var hoursDuration = duration.asHours();
console.log(hoursDuration);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data-2012-2022.js"></script>

Related

How to get difference between two datetime of moment.js?

How can I calculate the difference between two dates time in moment.js?
moment.duration((moment(startDate).format("MM-DD-YYYY h:mm:ss a")).diff(moment(new Date()).format("MM-DD-YYYY h:mm:ss a")));
and My startDate = 2022-02-02T12:12:25Z
I found the solution ,may help other people :
var now = moment(new Date(), "DD/MM/YYYY HH:mm:ss");
var then = moment(new Date(startDate), "DD/MM/YYYY HH:mm:ss");
var diffTime = moment.duration(then.diff(now));
and it depends to you how you want to get difference in seconds ,minutes or hours :
diffTime.asHours();

How to write a conditional for a time?

I'm trying to get a conditional what with the date of tomorrow example let me know what if is tomorrow and is more than 1pm of tomorrow so do something.
I work with MomentJs, so if you have a solution with this that can help me, is appreciated.
To get a Date for 13:00 tomorrow, you can create a date for today, add a day, then set the time to 13:00.
Then you can directly compare it to other dates using comparison operators < and > (but you need to convert both dates to numbers to compare as == or ===).
E.g.
// return true if d0 is before d1, otherwise false
function isBefore(d0, d1) {
return d0 < d1;
}
// Generate some sample dates
let now = new Date();
let d0 = new Date(now.setDate(now.getDate() + 1));
let d1 = new Date(now.setHours(10));
let d2 = new Date(now.setHours(15));
// Format output
function formatDate(d) {
let options = {day:'2-digit', month:'short', year:'numeric', 'hour-12':false, hour:'2-digit',minute:'2-digit'};
return d.toLocaleString('en-gb',options);
}
// Create a test date for 13:00 tomorrow
var testDate = new Date();
testDate.setDate(testDate.getDate() + 1);
testDate.setHours(13,0,0,0);
// Test it against sample dates
[d0,d1,d2].forEach(function(d) {
console.log(formatDate(d) + ' before ' + formatDate(testDate) + '? ' + isBefore(d, testDate));
})
In momentJS, you can get tomorrow by
const tomorrow = moment().add(1, 'days');
If you want to get tomorrow 1.00 PM then
var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');
If you want to compare, then
var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');
var current = moment();
if(current < tomorrow)
console.log('true');
else
console.log('false');

JavaScript Moment.js trying to get the difference between 2 datetimes

I am trying to get the difference between 2 datetimestamps which look like These:
2018-08-22 00:00:00
2018-08-11 15:34:31
I want to Show the difference in time in days - Hours - minutes - seconds left.
So far I did this but it Always return NaN:
import moment from 'moment';
const calc = {
render () {
moment().format();
this.calcDifference();
},
calcDifference() {
let releaseDate = document.getElementById('release-at').value;
let currentDate = document.getElementById('current-date').value;
let ms = moment(
releaseDate,
"DD-MM-YYYY HH:mm:ss").diff(moment(currentDate,
"DD-MM-YYYY HH:mm:ss")
);
let d = moment.duration(ms);
let s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log(ms);
console.log(d);
console.log(s);
}
};
calc.render();
on your calcDifference function, you can do something like this
let releaseDate = moment('2018-09-22 00:00:00');
let currentDate = moment('2018-08-11 15:34:31');
const diff = releaseDate.diff(currentDate);
const diffDuration = moment.duration(diff);
console.log(`
${diffDuration.months()} months
${diffDuration.days()} days
${diffDuration.hours()} hours
${diffDuration.minutes()} minutes
${diffDuration.seconds()} seconds left!`);
in case values from release-at and current-date elements have format
DD-MM-YYYY HH:mm:ss, use
let releaseDate = moment(document.getElementById('release-at').value, 'DD-MM-YYYY HH:mm:ss');
let currentDate = moment(document.getElementById('current-date').value, 'DD-MM-YYYY HH:mm:ss');
Here's a working codepen
I hope it helps! :)

Time duration calculation using javascript or jquery

Is it possible to do the below c# logic in javascript or jquery, The code converts duration between two dates int hours,minutes and seconds.the duration 20/01/2017 00:00:00 to 20/01/2017 02:20:30 will be 26:20:30
This about converting to hh:mm:ss format hours can go beyond 24, if minutes are more than 59 it should add to hours and seconds more than 59 should add to hours.
public static string ToTimeFormat(bool includeSeconds = false)
{
var startDate = DateTime.parse("20/01/2017 00:00:00";
var endDate = DateTime.parse("20/01/2017 02:20:30");
var ts = endDate - startDate;
var totalDaysToHours = ts.Days * 24;
return string.Format("{0}:{1}", (ts.Hours + totalDaysToHours).ToString("0"),
ts.Minutes.ToString("D2"))
+ (includeSeconds ? ":" + ts.Seconds.ToString("D2") : string.Empty);
}
You can use moment.js from here moment.min.js and below is the code
var startDate = "01/02/2016 00:00:00"; //MM/DD/YYYY HH:MM:SS format
var endDate = "01/03/2016 01:30:30"; //MM/DD/YYYY HH:MM:SS format
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(), diff.seconds()].join(':');
so your output will be like
26:30:30
UPDATE
var startDate = "01/02/2016 00:00:00".split(/\//);
startDate= [ startDate[1], startDate[0], startDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var endDate = "01/03/2016 01:30:30".split(/\//);
endDate = [ endDate[1], endDate[0], endDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(),diff.seconds()].join(':');

Javascript Date compare

In Javascript, if I have dates in the following string formats (mm/dd/yyyy)
date1 = "11/16/2015"
date2 = "11/09/2015"
date3 = "10/31/2015"
Can I directly run comparisions on them ?
like
date1 < date2
date2 > date3
is this the correct way to compare them ? Will it automatically consider the dates (like 31st Oct < 3rd Nov)
You cant do this with string format you have to convert your dates to Date() object before comparaison :
var date1_parts= date1.split("/");
date1 = new Date(date1_parts[2], date1_parts[0] - 1, date1_parts[1]);
var date2_parts= date2.split("/");
date2 = new Date(date2_parts[2], date2_parts[0] - 1, date2_parts[1]);
Now you can compare them using < or > signs :
date1 > date2
true
date1 < date2
false
date1 == date2
false
Hope this helps
You should convert to the date type then compare them
var d1 = new Date("11/16/2015");
var d2 = new Date("11/09/2015");
d1>d2 //true
d2>d1 //false
You can convert date into time format and then compare it.
date1 = new Date("11/16/2015").getTime();
date2 = new Date("11/09/2015").getTime();
date3 = new Date("10/31/2015").getTime();
// and then
// date1 < date2;
// date2 > date3;
// example
alert(date1 > date2);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime

Categories