I hope someone could help me on this...
I have this function and it is working as expected. It checks for leap year and takes 365 or 366 days accordingly.
Problem: Instead of checking leapyear, I want to check the fromdate and todate and if any of these dates start on 29 Feb and the difference between fromdate and todate is more than 365 only then add +1 to daysInYear otherwise consider only 365 days. I will not have any periods where 2 leap year will be in the given fromdate and todate. so I am not worried about that scenario.Hope it is clear.
getDifference: function(fromdate,toDate) {
var now = toDate || new Date();
// days since the date
var days = Math.floor((fromdate.getTime() - now.getTime())/1000/60/60/24);
var diff = 0;
// iterate the years
for (var y = now.getFullYear(); y <= fromdate.getFullYear(); y++){
var daysInYear = opc.calculator.leapYear(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
diff++;
// increment the age only if there are available enough days for the year.
}
}
return diff;
}
In case you don't mind adding a library to your code, have a look at: Moment.js
You do something like:
moment().diff(moment('20140229', 'YYYYMMDD'), 'days');
// returns 417 today (2015-04-22)
// or
moment('20150422', 'YYYYMMDD').diff(moment('20140229', 'YYYYMMDD'), 'days');
It is a great library to work with time and date.
Related
I have 2 dates like below :
Todays date = 2021-10-13 11:03:57.560
Old date = 2016-08-07 11:03:57.560
I want month difference from todays date Month - Old date Month = 10 - 8 = 2
Code:
console.log(moment().diff($scope.creationTime, 'months')); // returns 62
Expected: Current month - Old date month
Can anyone please help me with this?
Right now you get 62 because the two dates are 5 years and 2 months apart:
5 * 12 + 2 = 62
An easy way to drop the year difference is to use the remainder operator and do monthDifference % 12 which will give you only the number of months, regardless of the years:
function monthDiff(date1, date2) {
const monthDifference = moment(date1).diff(moment(date2), 'months');
return monthDifference % 12;
}
console.log(monthDiff("2021-10-13 11:03:57.560", "2016-08-07 11:03:57.560"));
console.log(monthDiff("2021-10-07 11:03:57.560", "2016-08-13 11:03:57.560"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Use month() from moment.js to get the months and simple math after that:
const today = moment();
const someday = moment('2011-01-01 00:00Z');
console.log(today.month())
console.log(someday.month())
console.log(Math.abs(today.month()-someday.month()))
You dont need moment to do that you use Date as well
new Date().getMonth - to get your current month
new Date('2016-08-07 11:03:57.560').getMonth() - to get the month of your old date
console.log(new Date().getMonth() - new Date('2016-08-07 11:03:57.560').getMonth())
I need to find out if my date is between two dates (for checking birthday whether its between +/- 10 days of current date) without taking care of year (because for birthday we don't need year).
I have tried the following but its typical match and will not ignore year. If i ll compare only date and month then overlap on month end makes problems.
(moment(new Date()).isBetween(moment(date).add(10, 'days'), moment(date).subtract(10, 'days')));
Here is the solution that i was end up with.
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = Math.abs(birthday - new Date) < 10*24*60*60*1000;
And if you are using moment then:
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = moment(new Date()).isBetween(moment(birthDate).subtract(10, 'days'), moment(birthDate).add(10, 'days'));
if(Math.abs(birthday - new Date) < 10/*d*/ * 24/*h*/ * 60/*min*/ * 60/*secs*/ * 1000/*ms*/)
alert("somewhat in the range");
You can just work with dates as if they were milliseconds. Just get the difference by subtracting them, then check if its smaller than 10 days in milliseconds.
You can use momentjs with methods subtract and add to find any date you want.
Example:
moment().add(7, 'days'); // next 7 days
moment().subtract(7, 'days'); // 7 days ago
This may be help you.
var birthDate = new Date("05/16/1993");
var day = birthDate.getDate();
var month = birthDate.getMonth();
var currentDate = new Date();
var tempDate = new Date();
var oneDay = 1000 * 60 * 60 * 24
var dayDifference = 10 // you can set here difference
tempDate = new Date(tempDate.setMonth(month,day))
var timeDiff = tempDate.getTime() - currentDate.getTime();
timeDiff = Math.round(timeDiff / oneDay)
if(-dayDifference <= timeDiff && timeDiff <=dayDifference){
alert("matched")
}
else{
alert("not matched")
}
Using this function in momentjs I can find the week number of the year:
var dt = new Date();
var weekNumber = moment(dt).week();
Can anyone tell me how to set the first week in April as week one, and therefore for week 52 to be the last week in March.
In the documentation I can only see how to adjust the first day of the year (ie Sunday or Monday). I need to do both. Saturday will actually be day one.
Help much appreciated.
You will have to add a custom function,
Sample
function getCustomWeekNumber(weekNo) {
var baseWeek = moment("01/04/", "DD/MM/").week() - 1; // 13
var lastWeek = moment("31/12/", "DD/MM/").week() //53;
return weekNo > baseWeek ? weekNo - baseWeek : (lastWeek - baseWeek) + weekNo;
}
var d = moment().week();
console.log(getCustomWeekNumber(d))
d = moment("01/04/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
d = moment("24/03/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>
I'm trying to get an age based on the end of the financial year.
If my date of birth is the 16th Jan 1962 my current age is 50 (assuming today's date is the 16th Jan 2012). What javascript formula/function could I use to calculate the age at the end of the current financial year (ie. 30th June 2012)?
This is what I have to get the current age:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
alert("current age "+age)
}
You would use the end of the current financial year as the "today" date, right? And then the end of the current financial year would either be hardcoded into the function, or figured out programmatically.
You simply need to calculate the difference between two dates:
function ageAtEOFY(birthDate) {
var eofy = new Date("2012-06-30");
var msDiff = eofy - new Date(birthDate);
return Math.floor(msDiff / 1000 / 60 / 60 / 24 / 365.25);
}
Used like this:
ageAtEOFY("1962-01-16"); // 50
ageAtEOFY("1984-11-14"); // 27
The way this works is that eofy - new Date(birthDate) gives you the difference between the two dates in milliseconds. The rest is just converting that value into years.
Note that there's a bit of a fudge here: leap years don't simply occur every four years.
Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp