How do I get the time difference between two different dates variables, specifically in years, months and days using moment.js?
I found this method but I keep getting weird results. Sometimes the result is one month ahead so I added a subtract one months part to make the result correct, but when the difference between the two dates can be divided into whole years it then becomes a month behind, but then if I remove the subtract month part, it gets even more out of whack.
Also I would like to format it as "X Years, Y Months, Z days", but also can't figure out how to format it in such way.
var dateOne = new Date(2000,07,16);
var dateTwo = new Date (1990,07,16);
var updatedDate = moment(dateOne).format('ll');
var x = moment(dateOne, 'DD/MM/YYYY').diff(moment(dateTwo, 'DD/MM/YYYY'))
var y = moment.duration(x);
var why = moment(x).subtract(1, 'M');
var z = Math.floor(y.asYears()) + moment.utc(why).format('/MM/DD');
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Try this perhaps?
var firstDate = moment();
var secondDate = moment("2018-03-19");
var yearDiff = firstDate.diff(secondDate, "year");
var monthDiff = firstDate.diff(secondDate, "month");
var dayDiff = firstDate.diff(secondDate, "day");
console.log(yearDiff + " Years, " + monthDiff + " Months, " + dayDiff + " Days");
https://jsfiddle.net/px1brLdk/
As stated by others in the comments, you can't format a duration as a date and since dateOne and dateTwo are a Date objects, there is no need for the second argument in moment(dateOne, 'DD/MM/YYYY'), simply use moment(Date).
Moverover, please note that when you use new Date(year, monthIndex, day) monthIndex starts from 0, see MDN docs:
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
You can use moment-duration-format plug-in to format momentjs duration according your needs, see format() docs on the plug-in page.
Here a live sample:
var dateOne = new Date(2000, 7, 16);
var dateTwo = new Date(1990, 7, 16);
var diff = moment(dateOne).diff(moment(dateTwo))
var dur = moment.duration(diff);
var result = dur.format();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
Moment is having a method called .diff() Use that one.
https://momentjs.com/docs/#/displaying/difference/
Related
I have a string in this format 201708 where the first four numbers are the year and the last two the month's. The result being a date of August 2017.
My first idea was to just make it to an date but won't work for me
var formattedDate = new Date("201708")
Thanks for any help
use substring() to split the string into year and month, then use those when calling Date().
let input = '201708';
let year = parseInt(input.substring(0, 4));
let month = parseInt(input.substring(5));
let date = new Date(year, month-1);
console.log(date);
You have to subtract 1 from month because JS counts months starting from 0.
Separate the date with a hyphen.
let b = "201708"
let b_with_hyphen = b.substring(0, 4) + "-" + b.slice(4)
// '2017-08'
let formattedDate = new Date(b_with_hyphen)
console.log(formattedDate.toUTCString())
I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js
I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/
Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.
I need to get the date one day after another date.
I do :
$scope.date2.setDate($scope.date1.getDate()+1);
if
$scope.date1 = 2015-11-27
then
$scope.date2 = 2015-11-28
It s ok,
but when
$scope.date1 = 2015-12-02
then
$scope.date2 = 2015-11-28 (ie tomorrow)
I don't understand why...
If anyone knows..
try this instead efficient simple pure JS
var todayDate = new Date();
console.log(new Date().setDate(todayDate.getDate()+1));
so you will have that same Date type object and hence you don't need to go with moment.js
Use moment.js for this momentjs
var startdate = "2015-12-02";
var new_date = moment(startdate, "YYYY-MM-DD").add('days', 1);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(new_date);
alert(day + '.' + month + '.' + year);
I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.
Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?
//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).
EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!
//Set the two dates
var currentTime = new Date()
var currDate = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.
//currDate = 8/17/12 and iniPastedDate = 8/7/12
function DateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value
}
//Write out the returning value should be using this example equal -10 which means
//it has passed by ten days. If its positive the date is coming +10.
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.
The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.
function setDateWeek(setDay){
var d = new Date();
d.setDate(d.getDate() - setDay); // <-- add this
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
return curr_date + "-" + curr_month + "-" + curr_year;
}
setDateWeek(1);
No need to include JQuery or any other third party library.
Specify your input date format in title tag.
HTML:
< script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">
Use javascript function:
IP_dateDiff(strDate1,strDate2,strDateFormat,debug[true/false])
alert(IP_dateDiff('11-12-2014','12-12-2014','DD-MM-YYYY',false));
IP_dateDiff function will return number of days.