I am trying to calculate the number of days between two dates using moment js.
function (value) {
var expiration= moment(value).format('DDMMYYYY');
var today = moment().format('DDMMYYYY');
var dayToExpiration = moment(expiration- today).format('D[days] ,H[hours]');
console.log(today + " : " + expiration
console.log(dayToExpiration);
The result is:
11102018 : 28102020 //--> 11.10.2018 : 28.10.2018
1 days ,6 hours //why only one day??
Because your dayToExpiration variable should be a moment.Duration object, not a string.
The difference between two datetimes is a duration, not a datetime.
Short answer:
As John Madhavan-Reese stated in his answer, you have to use moment Duration to represent the diffecence between two moments in time.
Issue in the code sample:
In your code you are creating a moment object from the difference between expiration and today. This value is interpreded by moment as the number of milliseconds since the Unix Epoch (see moment(Number)), so you are creating a moment object for a random day around the 1st January 1970 (see the output of moment(expiration- today).format() ). The D token in format() stands for Day of Month, so it gives an "incorrect" output.
My suggested solution:
You can calculate difference using momentjs' diff() then you can create a duration using moment.duration(Number).
Finally you can get your desired output using moment-duration-format plug-in (by John Madhavan-Reese :D)
Here a live sample:
function getDiff(value) {
var expiration= moment(value); // Parse input as momement object
var today = moment(); // get now value (includes current time)
// Calculate diff, create a duration and format it
var dayToExpiration = moment.duration(Math.abs(today.diff(expiration))).format('D[days], H[hours]');
console.log(today.format('DDMMYYYY') + " : " + expiration.format('DDMMYYYY'));
console.log(dayToExpiration);
}
getDiff('2018-10-28');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
I am getting errors. this one works for me:
moment.duration(expiration.diff(today))._milliseconds / (1000*60*60*24));
Related
How do I add minutes to this. I followed the documentation but somehow this is not working:
var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HHmm').format("HH:mm");
time.add(7,'m');
Only the last line is not working, but should be right according to the documentation. What am I doing wrong?
format returns a string, you have to use add on moment object.
Your code could be like the following:
var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HH:mm');
time.add(7,'m');
console.log(time.format("HH:mm"));
Note that you can create a moment object using moment(Object) method instead of parsing a string, in your case:
moment({hours: hours, minutes: minutes});
As the docs says:
Omitted units default to 0 or the current date, month, and year
You can use IF condition to see if minutes < 10
to add "0" like 07,08
var d = new Date()
var n = d.getMinutes()
if(n<10)
n="0"+n;
But watch out you will have to slice that zero if you want to increment.
i'm trying to calculate the difference between two UTC Datetime Strings with angular-momentjs like shown below:
var start = "1970-01-01T11:03:00.000Z";
var end = "1970-01-01T11:15:00.000Z";
var duration = $moment.utc($moment(end).diff($moment(start))).format("hh:mm");
when i execute the code above, the duration should be 00:12 but actually it is 12:12. I don't understand why and how to fix it.
You are actually creating a moment.js object for 1970-01-01T00:12:00.000Z, then getting the time as hour and minutes. The token "hh" is for 12 hour time, so you're seeing "12" for 12am. If you want to see 00:12, use the token "HH" which gives 24 hour time: 00:12.
I'm trying to get the difference in minutes between two timestamps
I have a timestamp that looks like this to begin with
'15:44:06'
And when I want to find the time elapsed I create a new moment timestamp
var currentTimestamp = Moment(new Date()).format('HH:mm:ss');
Which returns this
'15:42:09'
I then attempt to get the difference like so
var duration = Moment.duration(Moment(currentTimestamp,'HH:mm:ss').diff(Moment(userTimestamp,'HH:mm:ss')));
And then attempt to get it in minutes
var elapsedTime = duration().asMinutes();
console.log(elapsedTime);
But in the console when I log it I get this error
var elapsedTime = duration().asMinutes();
^
TypeError: object is not a function
I got most of this code from this stackoverflow
You can get the diff by using the moment constructor properly.
First, when you initialize your time stamp, you should use the following format:
var timestamp = moment('15:44:06','HH:mm:ss');
Second, when you want to use the diff function with the current time you should user it like so:
timestamp.diff(moment());
Then, the given number can be converted to minutes with .asMinutes() (the first )
for further information you should read the official docs here.
You can also try this with the lastest moment.js
var start = moment('15:44:06','HH:mm:ss');
var minutesPassed = moment().diff(start, 'minutes');
This question is getting a little bit old, this answer just bring the state up to date with a solution the question was looking for:
const startDate = moment();
...
elapsedDuration = moment.duration(moment().diff(startDate));
//in minutes
elapseDuration.asMinutes();
As per documentation about diff
and display duration in minutes
I need a regex which takes the string YYYY-MM-DD-XXXX (The last 4 are just for purpose of gender/area) It's mostly important to check the first 8 Digits for a valid birth date.
So far i have this:
/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})\-([0-9]{4})$/
Also i want to check so the input age is at least 18 years old. Would appreciate if somone had some input on how to achieve this.
Edit: The regex above was tested in JS, but should work fine in ASP as well?
I have changed your regex a bit to make it look more authentic
^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$
years like 3012 will not pass.
Now you want to find whether a person is 18 years or not.
One approach could be to find the difference between the years of dates provided like this
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var year_now = new Date().getFullYear();
console.log(year_now-res[1]);
a second approach will be more precise one :
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1],res[2],res[3]);
console.log(todays_date-birth_date);
will output the result in milliseconds. You can do the math to convert it into year
Cheers , Hope that helps !
I suggest using moment.js which provides an easy to use method for doing this.
interactive demo
function validate(date){
var eighteenYearsAgo = moment().subtract("years", 18);
var birthday = moment(date);
if (!birthday.isValid()) {
return "invalid date";
}
else if (eighteenYearsAgo.isAfter(birthday)) {
return "okay, you're good";
}
else {
return "sorry, no";
}
}
To include moment in your page, you can use CDNJS:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
Source
The following will match any year with a valid day/month combination, but won't do validation such as checking you've not entered 31 days for February.
^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])\-[0-9]{4}$
Not sure exactly what you're trying to achieve but I'd suggest using a date library for this sort of thing. You could return a message to the user somehow if the entered date fails to parse into an object.
In order to do age validation, you will certainly need to use a library so a regex should only be used for date validation purposes
I'm developing a custom validator of a date input in my workflow form and I get a null after parsing a date this is what I done:
// check dates can be parsed
str_expiryDate = field.form.prop_wfbxTestWorkFlow_NfDate.value;
console.log("Non conformite"+str_expiryDate);
str_reminderDate = field.form.prop_bpm_workflowDueDate.value;
console.log("echeance"+str_reminderDate);
Alfresco.logger.warn("Expiry Date: " + str_expiryDate + " | Reminder Date: " + str_reminderDate);
d_expiryDate = Date.parse(str_expiryDate);
console.log("nfDate"+str_expiryDate);
d_reminderDate = Date.parse(str_reminderDate);
console.log("Date echéance"+d_reminderDate);
and then i get this in console:
Non conformite2013-06-21T00:00:00.000+01:00 echeance2013-06-09T00:00:00.000+01:00
nfDatenull
Date echéancenull
How I can parse these two dates and then compare it? .thanks
Use Alfresco.util.fromISO8601(date)
According to the client-api docs
Convert an ISO8601 date string into a JavaScript native Date object
You are parsing the "value" of a date, not the date itself.
The best way to compare is, imho, using the format YYYYMMDD, and than compare it as a number.
Something like this (there is sure a far more elegant way to do that, but at this time it's the only one that got me):
var indexDate=str_expiryDate.indexOf("-");
var dayDate=str_expiryDate.substring(0, 2);
var monthDate=str_expiryDate.substring(3, 5);
var yearDate=fromData.substring(6, str_expiryDate.length+1);
int dataNew=yearDate+monthDate+dayDate;
and than compare the two dates value.
Obviously check if the index value are correct, I didn't double checked them.
Hope il helps.