Moment JS diff() returns 0 days between Oct 31 and 1 Nov - momentjs

As is shown below moment.diff() incorrectly calculates 0 days between yesterday (31 October) and today (1 November). Is this a problem with momentJS or with NodeJS (v14.15.4)?
> a = moment(new Date('2021-10-31'))
Moment<2021-10-31T02:00:00+02:00>
> b = moment(new Date('2021-11-01'))
Moment<2021-11-01T01:00:00+01:00>
> a.diff(b, 'days')
0
> a.diff(b, 'hours')
-24
One possible cause could be the summer => winter change that officially happened from Sun 31 Oct to Mon 1 Nov*. This is evident from the parsing of '2021-10-31' to a summer time Moment<2021-10-31T02:00:00+02:00> (2h).
Nevertheless, I would argue 24 hours diff should not come out as 0 days and thus it's a bug in Moment.
* Though everyone actually sets their clocks back on Sunday 31 Oct... go figure.

I think it's because there was the change of hour and that in .diff() for get the hour it's return a number lower than 1 and moment rounded it at 0.
You can change your code in that without use Date in the moment declaration:
const a = moment('2021-10-31');
const b = moment('2021-11-01');
console.log(a.diff(b, 'days')); // -1
console.log(a.diff(b, 'hours')); // -25 <- but this is wrong
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Or in alternative you can force that .diff() function returns a floating instead of integer putting the third parameter, and after round it like that:
const a = moment(new Date('2021-10-31'));
const b = moment(new Date('2021-11-01'));
console.log(Math.round(a.diff(b, 'days', true)));
console.log(Math.round(a.diff(b, 'hours', true)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Else is to force moment to use the utc date:
const a = moment.utc(new Date('2021-10-31'));
const b = moment.utc(new Date('2021-11-01'));
console.log(a.diff(b, 'days'));
console.log(a.diff(b, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related

What does NNN mean in date format <YYMMDDhhmmssNNN><C|D|G|H>?

hi I has date format and I want converted to correct GMT date :
<YYMMDDhhmmssNNN><C|D|G|H>
Sample value on that date:
210204215026000C
I get this explanation for part NNN :
NNN If flag is C or D then NNN is the number of hours relativeto GMT,
if flag is G or H, NNN is the number of quarter hours relative to GMT
C|D|G|H C and G = Ahead of GMT, D and H = Behind GMT
but I did not get how number of hours relative to GMT can present on 3 digits ? it should be in 2 digit as i knew the offset for hours related to GMT is from 0 to 23 , and also what quarter hours relative to GMT mean ?
I want to use Scala or Java.
I don’t know why they set 3 digits aside for the offset. I agree with you that 2 digits suffice for all cases. Maybe they just wanted to be very sure they would never run of out space, and maybe they even overdid this a bit. 3 digits is not a problem as long as the actual values are within the range that java.time.ZoneOffset can handle, +/-18 hours. In your example NNN is 000, so 0 hours from GMT, which certainly is OK and trivial to handle.
A quarter hour is a quarter of an hour. As Salman A mentioned in a comment, 22 quarter hours ahead of Greenwich means an offset of +05:30, currently used in Sri Lanka and India. If the producer of the string wants to use this option, they can give numbers up to 72 (still comfortably within 2 digits). 18 * 4 = 72, so 18 hours equals 72 quarter hours. To imagine a situation where 2 digits would be too little, think an offset of 25 hours. I wouldn’t think it realistic, on the other hand no one can guarantee that it will never happen.
Java solution: how to parse and convert to GMT time
I am using these constants:
private static final Pattern DATE_PATTERN
= Pattern.compile("(\\d{12})(\\d{3})(\\w)");
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuMMddHHmmss");
private static final int SECONDS_IN_A_QUARTER_HOUR
= Math.toIntExact(Duration.ofHours(1).dividedBy(4).getSeconds());
Parse and convert like this:
String sampleValue = "210204215026000C";
Matcher matcher = DATE_PATTERN.matcher(sampleValue);
if (matcher.matches()) {
LocalDateTime ldt = LocalDateTime.parse(matcher.group(1), FORMATTER);
int offsetAmount = Integer.parseInt(matcher.group(2));
char flag = matcher.group(3).charAt(0);
// offset amount denotes either hours or quarter hours
boolean quarterHours = flag == 'G' || flag == 'H';
boolean negative = flag == 'D' || flag == 'H';
if (negative) {
offsetAmount = -offsetAmount;
}
ZoneOffset offset = quarterHours
? ZoneOffset.ofTotalSeconds(offsetAmount * SECONDS_IN_A_QUARTER_HOUR)
: ZoneOffset.ofHours(offsetAmount);
OffsetDateTime dateTime = ldt.atOffset(offset);
OffsetDateTime gmtDateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("GMT time: " + gmtDateTime);
}
else {
System.out.println("Invalid value: " + sampleValue);
}
Output is:
GMT time: 2021-02-04T21:50:26Z
I think my code covers all valid cases. You will probably want to validate that the flag is indeed C, D, G or H, and also handle the potential DateTimeException and NumberFormatException from the parsing and creating the ZoneOffset (NumberFormatException should not happen).

MomentJS comparing Unix time with minutes and get difference

I need to find if currentDate time (unix) and lastFetchedTime(unix) is greater than 30 minutes in moment.js.
How can compare the subtracted value from 30 minutes in moment?
lastFetchedTime(unix) is equivalent to the previous Date.now()..
const now = moment(Date.now());
const lastFetched = 1598578706;
const checkTime = now.diff(lastFetched, 'minutes') > 30 ;
You can use momentJS duration function to get the difference between two times which are in unix format.
Firstly, you need to convert the unix format to human readable time and then get the difference of current time and lastFetched time using asMinutes function of duration
If the difference is greater then 30 then do something else or do something else.
Live Demo:
const now = moment().unix()
const lastFetched = 1598597404;
const duration = moment.duration(moment.unix(now).diff(moment.unix(lastFetched)));
const getMinutes = duration.asMinutes();
if (getMinutes > 30) {
console.log('Minutes are GREATER then 30 minutes - from now')
} else {
console.log('Minutes are LESS then 30 minutes - from now')
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

Momentjs - Add days with specific time

I'm using momentjs to calculate certain dates. For example:
moment().add(7, 'days');
This returns date in 7 days in same time like now:
Thu May 21 2020 12:06:35 GMT+0200.
What is the function for adding days but in specific time like:
Thu May 21 2020 17:00:00 GMT+0200.
You could chain the add() to get add hours,minutes,seconds.
console.log('Current time: ', moment().format("DD-MM-YYYY hh:mm:ss"));
var start_time = moment()
.add(1, "days")
.add(4, "hours")
.add(21, "seconds");
console.log('modified time: ', start_time.format("DD-MM-YYYY hh:mm:ss"));
<script src="https://momentjs.com/downloads/moment.js"></script>
I found a solution:
moment({ hour: 17 }).add(7, 'd')
This ads exactly 7 days to today in 17:00:00.

Moment JS getting Date without time [duplicate]

formatCalendarDate = function (dateTime) {
return moment.utc(dateTime).format('LLL');
};
It displays: "28 februari 2013 09:24"
But I would like to remove the time at the end. How can I do that?
I'm using Moment.js.
Sorry to jump in so late, but if you want to remove the time portion of a moment() rather than formatting it, then the code is:
.startOf('day')
Ref: http://momentjs.com/docs/#/manipulating/start-of/
Use format('LL')
Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:
Moment().format('LL'); // => April 29, 2016
The correct way would be to specify the input as per your requirement which will give you more flexibility.
The present definition includes the following
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
You can use any of these or change the input passed into moment().format().
For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').
Okay, so I know I'm way late to the party. Like 6 years late but this was something I needed to figure out and have it formatted YYYY-MM-DD.
moment().format(moment.HTML5_FMT.DATE); // 2019-11-08
You can also pass in a parameter like, 2019-11-08T17:44:56.144.
moment("2019-11-08T17:44:56.144").format(moment.HTML5_FMT.DATE); // 2019-11-08
https://momentjs.com/docs/#/parsing/special-formats/
You can also use this format:
moment().format('ddd, ll'); // Wed, Jan 4, 2017
formatCalendarDate = function (dateTime) {
return moment.utc(dateTime).format('LL')
}
Look at these Examples.
Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 7th 2020, 9:58:18 am
moment().format('dddd'); // Monday
moment().format("MMM Do YY"); // Dec 7th 20
moment().format('YYYY [escaped] YYYY'); // 2020 escaped 2020
moment().format(); // 2020-12-07T09:58:18+05:30
Relative Time
moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 8 years ago
moment().startOf('day').fromNow(); // 10 hours ago
moment().endOf('day').fromNow(); // in 14 hours
moment().startOf('hour').fromNow(); // an hour ago
Calendar Time
moment().subtract(10, 'days').calendar(); // 11/27/2020
moment().subtract(6, 'days').calendar(); // Last Tuesday at 9:58 AM
moment().subtract(3, 'days').calendar(); // Last Friday at 9:58 AM
moment().subtract(1, 'days').calendar(); // Yesterday at 9:58 AM
moment().calendar(); // Today at 9:58 AM
moment().add(1, 'days').calendar(); // Tomorrow at 9:58 AM
moment().add(3, 'days').calendar(); // Thursday at 9:58 AM
moment().add(10, 'days').calendar(); // 12/17/2020
Multiple Locale Support
moment.locale(); // en
moment().format('LT'); // 9:58 AM
moment().format('LTS'); // 9:58:18 AM
moment().format('L'); // 12/07/2020
moment().format('l'); // 12/7/2020
moment().format('LL'); // December 7, 2020
moment().format('ll'); // Dec 7, 2020
moment().format('LLL'); // December 7, 2020 9:58 AM
moment().format('lll'); // Dec 7, 2020 9:58 AM
moment().format('LLLL'); // Monday, December 7, 2020 9:58 AM
moment().format('llll'); // Mon, Dec 7, 2020 9:58 AM
Whenever I use the moment.js library I specify the desired format this way:
moment(<your Date goes here>).format("DD-MMM-YYYY")
or
moment(<your Date goes here>).format("DD/MMM/YYYY")
... etc I hope you get the idea
Inside the format function, you put the desired format. The example above will get rid of all unwanted elements from the date such as minutes and seconds
With newer versions of moment.js you can also do this:
var dateTime = moment();
var dateValue = moment({
year: dateTime.year(),
month: dateTime.month(),
day: dateTime.date()
});
See: http://momentjs.com/docs/#/parsing/object/.
You can use this constructor
moment({h:0, m:0, s:0, ms:0})
http://momentjs.com/docs/#/parsing/object/
console.log( moment().format('YYYY-MM-DD HH:mm:ss') )
console.log( moment({h:0, m:0, s:0, ms:0}).format('YYYY-MM-DD HH:mm:ss') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
For people like me want the long date format (LLLL) but without the time of day, there's a GitHub issue for that: https://github.com/moment/moment/issues/2505. For now, there's a workaround:
var localeData = moment.localeData( moment.locale() ),
llll = localeData.longDateFormat( 'llll' ),
lll = localeData.longDateFormat( 'lll' ),
ll = localeData.longDateFormat( 'll' ),
longDateFormat = llll.replace( lll.replace( ll, '' ), '' );
var formattedDate = myMoment.format(longDateFormat);
Try this:
moment.format().split("T")[0]
The thing is - you can run into an issue with timezones. For example, if you parse date like this: '2022-02-26T00:36:21+01:00' it may turn into '25/02/2022' As a solution if your date is in ISO format you can just cut off the time portion from the string, like this:
moment('2022-02-26T00:36:21+01:00'.split('T')[0]).utc().format('DD/MM/YYYY')
This solution is quite blunt, so be careful with string format.
This format works pretty fine
const date = new Date();
const myFormat= 'YYYY-MM-DD';
const myDate = moment(date, 'YYYYMMDDTHHmmss').format(myFormat);
Try
new Date().toDateString()
Result - "Fri Jun 17 2022"
This worked perfectly for me:
moment().format('YYYY-MM-DD')
moment(date).format(DateFormat)
Here DateFormat should be DateFormat = 'YYYY-MM-DD'

momentjs calculates date difference incorrectly

In my angular web application, I want to compare two dates to see if a person is less than 18 years old when she/he entered the company. Here is the code I use to do this:
const dayOfBirth = moment(formControl.value, this.dateFormat, true).startOf('day');
const entranceDateControl = this.wizardFormGroup.get('entranceDate');
const entranceDate = moment(entranceDateControl.value, this.dateFormat, true).startOf('day');
// Check validation rule R3: Age is less than 18 compared to entrance date
const difference = moment.duration(Math.abs(entranceDate.diff(dayOfBirth)));
if (difference.years() < 18) {
const validationMessage = this.getValidationMessage('R3', formControlName);
return validationMessage ? validationMessage.message : null;
}
As you can see, I am using startOf('day') to get rid of any time component so that I only handle dates. I use diff() to get the difference between two dates and then duration() to convert the difference to years, months, days, etc. Using this code, the validation message should NOT show when the person is turning 18 years old on the day when she/he entered the company.
Upon testing this, I came across what is, in my opinion, strange behavior. Depending on months and years used, it gave different results. For instance, for these dates it was Ok:
dayOfBirth = 1998-03-01, 1998-04-01, ..., 2000-02-01
entranceDate = 2016-03-01, 2016-04-01, ..., 2018-02-01
But the following dates returned the validation message:
dayOfBirth = 2000-03-01, 2000-04-01, ..., 2002-02-01
entranceDate = 2018-03-01, 2000-04-01, ..., 2020-02-01
After these dates, i.e. using 2002-03-01 and onward, it works again. I also got wrong result for the dates preceding 1998-03-01.
Now, I had a closer look at the Duration object and I noticed that for the times where it was less than 18 years, it had calculated 864 milliseconds less then when it came to the right conclusion that it was 18 years between the dates.
Correct duration
----------------
dayOfBirth = 1998-03-01, 1998-04-01, ..., 2000-02-01
entranceDate = 2016-03-01, 2016-04-01, ..., 2018-02-01
Duration = 568080000000 ms
Wrong duration
--------------
dayOfBirth = 2000-03-01, 2000-04-01, ..., 2002-02-01
entranceDate = 2018-03-01, 2000-04-01, ..., 2020-02-01
Duration = 567993600000 ms
Duration difference
-------------------
568080000000 - 567993600000 = 86400000 ms = 24 hours = 1 day
Has anyone an explanation for this? Can it be considered a bug in momentjs? Any viable workaround for this?
I didn't go into details in moment source code but it seems duration() is playing tricks with you. Simplify the code and rely only on diffas follow and you should be good (at least it seems to work for the samples you provided). And it's easier on the eyes :)
const moment = require('moment')
const dayOfBirth = moment('2000-03-01').startOf('day');
const entranceDate = moment('2018-03-01').startOf('day');
const difference = entranceDate.diff(dayOfBirth, 'years')
if (difference < 18) {
console.log( '<18')
} else {
console.log( '>=18')
}
will output >=18

Resources