Moment JS days difference issue - javascript

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>

Related

Moment js. Comparison two dates

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'));

Days between dates in DayJS UK Format

Im using dayjs, and I'm trying to calculate the days between 2 days so that I can output Today, Tomorrow and X days time
The problem I'm having though seems to be with the date formats
const date1 = dayjs('31/10/2021');
const date2 = dayjs().format("DD/MM/YYYY")
let hours = date2.diff(date1, 'days')
No matter how I try, I'm getting date2.diff is not a function when I add .format to date2. Does anyone know how to format this correctly and get the correct outcome?
If i try const date1 = dayjs('31/10/2021').format("DD/MM/YYYY"); then it errors with invalid date
You can try the following:
const date1 = dayjs('2021-01-25');
const date2 = '01/11/2020'; // or '2020-11-01'
let hours = date1.diff(date2, 'day')
console.log(hours) // 380
The format function just returns a string. This is why date2.diff is not a function.
The diff function is only available for dayjs objects (not for strings).
Docs for difference function: https://day.js.org/docs/en/display/difference
Docs for format function: https://day.js.org/docs/en/display/format
const date1 = dayjs('2019-01-25')
date1.diff('2018-06-05', 'day', true)
You don't need to call format function, just use dayjs constructor to convert both dates to dayjs object and return the difference between the 2 dates in number of days.

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

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

Why is the value output by MomentJS not reflecting UTC time?

I am trying to get a particular day/time in UTC format. Example code
const today = moment().tz('America/New_York')
const tomorrow = today.add(1, 'days')
const formatTime = today.format('YYYY-MM-DD')
const time = '7:00 pm'
const deliveryTime = moment(`${formatTime} ${time}`)
console.log(deliveryTime.utc().format())
Shouldn't I be getting this as output 2019-10-01T19:00:00Z as I am getting it on https://repl.it/#azs06/SilkyBronzeInversion
Suppose to 2019-10-02T13:00:00Z this on https://jsfiddle.net/azs06/hkrvze1x/2/
Is this is because of Node.js implementation of date?
What would be proper way to convert date time to UTC using moment.js?

How to change current date -7 days from now - [PersianDatepicker]

I am using Babakhani Datepicker and actually i have done substract thing from datepicker but it does not work on this , so i want to cast -7 days from currentdate
I have done it on console Like this
var nowDate = new Date();
var days = 7;
nowDate.setDate(nowDate.getDate() - days);
var mamat = nowDate.toISOString().split('T')[0];
console.log(mamat);
but as i am using PERSIAN not GREGORIAN i cant convert it
I have to use it on this
$(".persianDate").pDatepicker();
today date is 1/13/2019
and i want it to be 1/7/2019
Babakhani Source :
http://babakhani.github.io/PersianWebToolkit/doc/datepicker/options/
let date = new Date();
date.setDate(date.getDate()-1);
console.log(date.toLocaleDateString());
// Woud log:
// 1/12/2019
console.log(date.toLocaleDateString('fa-IR'));
// Woud log:
// ۱۳۹۷/۱۰/۲۲
If you want to set the calendar, then you can pass the desired calendar as an argument to the toLocaleDateString method, as per the MDN docs. For example, passing 'ar-EG' will result in Arabic digits.
Possible duplicate of Subtract days from a date in JavaScript.

Categories

Resources