MomentJS comparing Unix time with minutes and get difference - momentjs

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>

Related

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

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>

Getting one hour less in time when converting to UTC via moment - utcOffset not working

When converting time to UTC its showing one hour less than expected
I am updating a variable of dot net via moment to convert the time & show local system time to user. But post conversion i am getting one hour less. Tried utcOffset but getting error utcOffset is not a function. any suggestion
Where formData.SubmittedDate = "6/7/2019 5:44:59 AM"
$('[data-utcdate]').each(function () {
var d = moment($(this).attr('data-utcdate'));
//var isDST = d.utc().local().isDST();
//var d = moment(d).utcOffset(d);
d = d.utc();
$(this).html(d.format('MMM D, YYYY h:mm A'));
})
Getting :Jun 7, 2019 12:14 AM
Expected : Jun 7, 2019 11:44 AM
From the docs:
Get the UTC offset in minutes.
So you could use a manipulation method like add with it:
$('[data-utcdate]').each(function () {
var d = moment($(this).attr('data-utcdate'));
var offset = d.utcOffset() // will return the offset in minutes
var time = d.add(offset, "m");
$(this).html(time.format('MMM D, YYYY h:mm A'));
})

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

Check whether a timestamp is 1 hour old - Groovy

I have a timestamp (submitTime) which I need to check whether it is less than 1 hour old or not. Timestamps are in microseconds and including date.
currentTime = 1527530605357000000 (Monday, May 28, 2018 6:03:25.357 PM)
submitTime = 1527529918658907821 (Monday, May 28, 2018 5:51:58.659 PM)
long currentTime = (long) (new Date().getTime()*1000000)
submitTime = job.SubmitTime // part of the code
oneHhour = 3600000000
if (currentTime - submitTime > oneHhour) {
println job.Name + " env is up more than 1 hour";
But it doesn't work since the result is 686698092179 and it it not represent time.
Help?
Assuming SubmitTime is a timestamp in microseconds, you can compare it the the current timestamp in microseconds like so:
// Get the current time (System.currentTimeMillis) in microseconds:
long currentMicroseconds = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())
// You could also simply do this:
long currentMicroseconds = System.currentTimeMillis() * 1000
// Subtract the timestamps and compare:
if (currentMicroseconds - job.SubmitTime > 3600000000) {
// More than an hour has elapsed
}
The timestamp is assumed to be the number of microseconds since January 1, 1970, 00:00:00 GMT (consistent with Date.getTime).
In groovy you can use TimeCategory which is much more intuitive:
def date = new Date(timestampInLong)
use (groovy.time.TimeCategory) {
println (date > new Date() - 1.hour)
}

Groovy Time durations

I'm trying to get the difference between 2 dates in days, hours, and seconds:
import groovy.time.*
Date now = new Date()
// Using deprecated constructor just for this example
Date newYearsDay2000 = new Date(2000, 0, 1)
use (TimeCategory) {
now - newYearsDay2000
}
This prints:
-690023 days, -14 hours, -38 minutes, -27.182 seconds
Which is obviously nothing like the difference between today's date and 2000/1/1, where am I going wrong?
Thanks,
Don
Could be an issue with the deprecated constructor?
If you use Calendar (and the Groovy updated method) to create the newYearsDay2000 var, you get:
import groovy.time.*
import static java.util.Calendar.*
Date now = new Date()
// Use the static imported Calendar class
Date newYearsDay2000 = instance.updated( year:2000, month:JANUARY, day:1 ).time
use( TimeCategory ) {
now - newYearsDay2000
}
which gives the result:
3925 days, 23 hours, 59 minutes, 59.999 seconds
Edit
Yeah, the JavaDoc for Date shows that constructor with the comment:
Date(int year, int month, int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Which leads me to believe that:
Date newYearsDay2000 = new Date(2000, 0, 1)
Is actualy creating the Date for new Years Day in the year 3900
Date
Parameters:
year - the year minus 1900.

Resources