How to compare two dates with moment js. I used diff() method , but not worked. How I solve it ?
let lastMessageMinute = moment("06-30-2022").format("HH:mm");
let currentTime = moment(new Date()).format("HH:mm");
const differenceOfTimes = currentTime.diff(lastMessageMinute, "hours");
Convert both dates (before formatting) to milliseconds and compare them. Like
if(lastMessageMinute.valueOf() === currentTime.valueOf())
you need to do like moment().diff()
Your syntax -> moment().format().diff() this is not accept by moment js.
For Example,
var a = moment("18.05.2022", "DD.MM.YYYY");
var b = moment(new Date(), "DD.MM.YYYY");
console.log("diff", b.diff(a, 'hours'));
Related
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work
I'm calculating the days difference between two dates using moment.js, but seems it wasn't calculated correctly.
const moment1 = moment(new Date('2020-04-05'));
const moment2 = moment(new Date('2020-01-06'));
const diff = moment1.diff(moment2 , 'days');
console.log(diff);
The output is 89 whereas the actual value should be 90. Specifically, if I change moment1 to '2020-04-04', the output is still 89. But after '2020-04-05' the value is always 1 day less than the actual value. Why?
You can simply pass dates you are checking for difference instead of using new Date() There is not requirement to use new Date() at all
Simple pass the date as string to moment and you will have 90 days.
Here is what moment.js diff says.
Run snippet below.
const moment1 = moment('2020-04-05');
const moment2 = moment('2020-01-06');
const diff = moment1.diff(moment2 , 'days')
console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()
i wanted to get the difference of two timestamps of different timezone in javascript:
var firstTime ="2017-07-21 04:34:21";
var timeZone1:"+0100";
var secondTime ="2017-07-21 04:36:27";
var timeZone2:"+0124";
How we can get the difference in miliseconds ?
Convert your strings into ISO 8601 formats. These generally work well in JavaScript Date constructors. Then simply subtract one from the other
var firstTime ="2017-07-21T04:34:21";
var timeZone1 = "+01:00";
var secondTime = "2017-07-21T04:36:27";
var timeZone2 = "+01:24";
const firstDate = new Date(firstTime + timeZone1)
const secondDate = new Date(secondTime + timeZone2)
console.log('firstDate', firstDate)
console.log('secondDate', secondDate)
console.info('diff', firstDate - secondDate)
you can use moment.js (https://momentjs.com/) for get the current timestamp from different time zone.
But donĀ“t forget : "Time Zone != Offset"
https://stackoverflow.com/tags/timezone/info
Another good example:
Get timezone difference in hours with moment
I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}
Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));
The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);
You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);
for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?