This is my code:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var startDate = new Date( date1.split("/")[2], date1.split("/")[1]-1, date1.split("/")[0] );
var endDate = new Date( date2.split("/")[2], date2.split("/")[1]-1, date2.split("/")[0] );
var diff = new Date(endDate - startDate);
var diffResult = ((diff.getFullYear() - 1970) * 12+ diff.getMonth()) + " months";
so the output is only 35 months (and also 30 days but its hidden)
but as 30 days are actually already a month, I would like to have it as 36 months.
any suggestions?
thanks
There are several good thoughts/solutions in the comments. It seems what you're really after is the number of 30-day intervals that fit between the start and end date.
After all, 30 days is not always a month as months can have 31 days.
If you're interested in how many 30-day intervals fit between a start and end date you can count the days and divide by 30:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var dateRegex = /\d+/g;
var date1Array = date1.match(dateRegex);
var date2Array = date2.match(dateRegex);
var startDate = new Date(date1Array[2], date1Array[1], date1Array[0]);
var endDate = new Date(date2Array[2], date2Array[1], date2Array[0]);
var diffResult = Math.round((endDate-startDate)/(1000*60*60*24));
var months = Math.floor(diffResult/30);
alert(months);
Credit for the equation to get the number of days goes to this question.
Related
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'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console
Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );
actually the code works fine when the date is on the same month but i had a problem when the date is on the different month like 30/09/2015 and 01/10/2015 the number of days result is 2.(sorry for my bad english)
Here's the sample code:
var dtElem1 = '30/09/2015';
var dtElem2 = '01/10/2015';
var resultElem = frm.elements['numberofdays'];
var oneDay = 24*60*60*1000;
var x = dtElem1.value;
var y = dtElem2.value;
var arr1 = x.split('/');
var arr2 = y.split('/');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
resultElem.value = Math.round(Math.abs((dt1.getTime() -
dt2.getTime())/(oneDay)));
The Date methods count months from zero, so you should substract 1 from the month number when setting the date. That explains your bug, since you end up substracting the 30th of october from the 1st of november and october has 31 days.
This will give the expected result:
dt1.setFullYear(arr1[2], arr1[1] - 1, arr1[0])
dt2.setFullYear(arr2[2], arr2[1] - 1, arr2[0])
Note that you don't need to create the Date and then set it. You can pass the same arguments directly to the constructor:
dt1 = new Date(arr1[2], arr1[1] - 1, arr1[0])
dt2 = new Date(arr2[2], arr2[1] - 1, arr2[0])
How do I calculate the age of a user, depending on the date entered in a textbox?
I want to be able to calculate the exact age of YYYY/MM/DD, so far I've only managed to do it by year.
The code I've tried so far:
function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;
}
Any ideas?
When you set the date using this: new Date(birthYear, birthMonth, birthDay); you need to subtract 1 from the month. Months are counted from 00.
For example,
var testDate = new Date(1988,10,12) is Sat Nov 12 1988 00:00:00
You can try this alternate way:
var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
age--;
}
console.log(age);
This will return you the correct age based on input birth date.
well since i can't make comment, im gonna do it here.
first thing i would do is use momentjs for every date releated thing in js
and if i understand your right, you want something like this?
How to get difference between 2 Dates in Years, Months and days using moment.js
You can use Math.floor and the modulo operator % for integer division:
function CalculateAge() {
var dob1 = $("#txtBirthday").val();
var age1 = document.getElementById("#age");
var dateAry = dob1.value.split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var birthDate = new Date(birthYear, birthMonth, birthDay);
var currentDate = new Date();
var age = currentDate - birthDate; // don't forget the var keyword
var days = Math.floor(age / 86400000); // no need to use a string
var years = Math.floor(days / 365); // quite inaccurate actually
var remaning_days = days % 365; // use modulo operator
age1.value = years; // no need to type-cast
}
function CalculateAge() {
var dob1 = $("#txtBirthday");
var age1 = $("#age");
var dateAry = dob1.val().split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var one_day=1000*60*60*24;
var date1 = new Date(birthYear, birthMonth, birthDay);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2 = new Date();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var t = difference_ms/one_day;
age1.val(t/365);
}
if you want approx year use Math.random in result