I am trying to code a function that when given a past date will calculate years, months, and days since then in a trickle down remainder fashion. As in "2 years, 1 month, and 3 days.", not total time in all 3 formats (2 years = 24 months = 730 days).
Code:
//Function to tell years/months/days since birthday to today
var ageID = function(date){
var nowDate = new Date();
//current date
var nowYear = nowDate.getFullYear();
var nowMonth = nowDate.getMonth();
var nowDay = nowDate.getDay();
//input birthday
var year = date[0];
var month = date[1];
var day = date[2];
var longMonth = [1, 3, 5, 7, 8, 10, 12];
var shortMonth = [4, 6, 9, 11];
var febMonth = [2];
var specfMonth = 0;
//finding month that corresponds to 28, 30, or 31 days in length
for (i = 0; i < longMonth.length; i++){
if (longMonth[i] === month){
specfMonth = 31;
}
}
for (i = 0; i < shortMonth.length; i++){
if (shortMonth[i] === month){
specfMonth = 30;
}
}
for (i = 0; i < febMonth.length; i++){
if (febMonth[i] === month){
specfMonth = 28;
}
}
//Reduced input and current date
var redYear = nowYear - year - 1;
var redMonth = 0;
var redDay = 0;
//The following 2 if/else are to produce positive output instead of neg dates.
if (nowMonth < month){
redMonth = month - nowMonth;
}else{
redMonth = nowMonth - month;
}
if (nowDay < day){
redDay = day - nowDay;
}else{
redDay= nowDay - day;
}
var adjMonth = 12 - redMonth;
var adjDay = specfMonth - redDay;
if (redYear < 1){
return adjMonth + " months, " + adjDay + " days ago.";
}else{
return redYear + " years, " + adjMonth + " months, " + adjDay + " days ago.";
}
};
console.log(ageID([2001, 9, 11]));
Output:
13 years, 10 months, 20 days ago.
However, the accurate output would be:
13 years, 10 months, 30 days ago.
Your issue is : var nowDay = nowDate.getDay();
You should use: nowDate = nowDate.getDate(); instead.
getDay() return the number of day in the week.
Monday is "1", Tuesday is "2", etc.
Related
How to can I make this sequence of date with tri-monthly. for eg. the input is `"2022-03-14" the input is dynamic it depends on the user input... I'm trying add + 10 days but isn't working
The output I want
[
"2022-03-24",
"2022-04-04",
"2022-04-14",
"2022-04-24",
"2022-05-04",
"2022-05-14",
"2022-05-24",
"2022-06-04",
"2022-06-14",
"2022-06-24",
]
My code output which is worng
[
"2022-03-24",
"2022-04-14",
"2022-04-24",
"2022-05-14",
"2022-05-24",
"2022-06-14",
"2022-06-24",
"2022-07-14",
"2022-07-24",
]
function createSchedule(date, count){
date = new Date(date);
let day = date.getDate();// Get day in given date
let k = 0;
let days = k? [day - 10, day , day + 10] : [day, day + 10, day- 10];
let result = [];
if(day > 10){
k = +0
}else{
if(day > 20 ){
k = +1
}else{
k= +2
}
}
for(let i = 0; i < count; i++){
k= 1-k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result
}
var dateRelease = new Date("03-14-2022");
var result = createSchedule(dateRelease, 9);
console.log(result)
A few issues in your attempt:
After let k = 0, the conditional operator on k? will always evaluate the first expression after ?, which is [day - 10, day , day + 10].
That array could have dates that are greater than 31 (day + 10)
That other array [day, day + 10, day- 10] is not sorted, but should be.
The constants +0 and +1 and +2 are OK, but it looks odd that you use the unary plus here. It could just be 0, 1 and 2.
The assignment k = 1 - k assumes you only have two entries in your days array, but you have three, so use modular arithmetic: k = (k + 1) % 3
Here is a correction:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let firstDay = 1 + (day - 1) % 10;
let days = [firstDay, firstDay + 10, firstDay + 20];
let k = days.indexOf(day);
let result = [];
for (let i = 0; i < count; i++) {
k = (k + 1) % 3;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-03-14");
var result = createSchedule(dateRelease, 25);
console.log(result);
I got lot of selected data from fullcalendar. I need to get those selected date from one whole year. How to check that in for loop?
I tried few answers to add days one by one to my condition from some answers ,but its not working for me.
Here is my code I tried:
var t=$(#dttbl).datatable();
var arr = new Array();
var date = new Date(),
var Id = 1;
var d = date.getDate(),
month = date.getMonth(),
year = date.getFullYear()
var day1 = y + '-01-01';
var day365 = y + '-12-31';
for (i = day1; i < day365; day1.setdate(day1.getdate() + 1)) {
if (($(i.cell).css('backgroundColor', 'blue'))) {
arr.push(([Id,i,'test']));
Id++;
}
}
for (i = 0; i < arr.length; i++) {
t.row.add([
arr[i][0],
arr[i][1],
arr[i][2]
]).draw();
}
I tried this getdate(), day1.add(1).day(); , day1=moment(day1).add(1, 'days') to add one by one day to check my condition for full year? These are not working for me. Is there any other way to do it?
You can use the following as #mplungjan commented.
var arr = [];
var date = new Date('01-01-2019');
var DAY = 1000 * 60 * 60 * 24;
var day1 = date.getTime();
var day365 = day1+ 365*DAY;
var iDay = day1;
while(iDay < day365){
// pushing the value in arr for example.
arr.push(new Date(iDay));
// do your logic
iDay = iDay + DAY;
}
You can use daysInMonth function of moment.js to find how many days in each month. After that you can create your array.
var dates = [];
var year = new Date().getFullYear();
for (var i = 1, l = 12; i <= l; i++){
var daysInMonth = moment("2012-" + i, "YYYY-M").daysInMonth();
console.log("month : " + i)
console.log("days in month : " + daysInMonth)
for (i1 = 1, l1 = daysInMonth; i1 <= l1; i1++) {
dates.push(year + "-" + i + "-" + i1)
}
}
console.log(dates);
I want to calculate the timespan between two dates (note: input format is dd.MM.yyyy, see code below). Special thing is, that don't want to use 30 days for every month and 360 days for a year. I rather want the difference in "human format" (don't know how to call it).
Let's say, I want to calculate difference (including the last day) from October 1 (2014) until March 17, 2015. From October to February this would make 5 months. And then the rest would be 18 days (from day 1 to 17, including 17th day). So the result should be :
0 years, 5 months, 18 days
This sort of calculation of course ignores that some months have 31, 30, 28 or 29 days (except for the day calculation, when dates are in such a form: start date: October 17th, 2014; end date: Januar 12th, 2015).
Unfortunately I didn't found any JS lib that already implements this sort of calculation. Moments.js, doesn't seem to have any methods for this.
So I started creating my own code but I'm still always off some days (2-3 days) from the expected result. And to be honest, if I look at my code I have the feeling that it sucks and there must be a more intelligent and elegant way to calculate this (in my example I'm outputting it to a span):
function getTimeDifferenceContract(startDateStr, endDateStr) {
var returnObject = { "years": null, "months": null, "days": null };
var startDateArray = startDateStr.split('.');
var endDateArray = endDateStr.split('.');
var startMonthIx = startDateArray[1]-1;
var endMonthIx = endDateArray[1]-1;
var startDate = new Date(startDateArray[2], startMonthIx, startDateArray[0]);
var endDate = new Date(endDateArray[2], endMonthIx, endDateArray[0]);
var endDateFixed = new Date(endDate.getTime()+(1*24*60*60*1000));
if (endDate > startDate) {
var years = 0;
var months = 0;
var days = 0;
var dateDiff = endDateFixed.getTime() - startDate.getTime();
var sD = startDate.getDate();
var sM = startDate.getMonth()+1;
var sY = startDate.getFullYear();
var eD = endDateFixed.getDate();
var eM = endDateFixed.getMonth()+1;
var eY = endDateFixed.getFullYear();
if (sY == eY && sM == eM) {
days = Math.floor(dateDiff / (1000 * 60 * 60 * 24));
}
else if (sY == eY) {
if (sD > eD) {
months = eM - sM - 1;
var startMonthRestDays = getMonthdays(sM, sY) - sD;
days = startMonthRestDays + eD;
}
else {
months = eM - sM;
days = eD - sD;
}
}
else {
years = eY - sY - 1;
var monthForYears = 0;
if (years > 0) {
monthForYears = (years - 1) * 12;
} else {
monthForYears = years * 12;
}
months = (12 - sM) + (eM - 1) + (monthForYears)
var startMonthRestDays = getMonthdays(sM, sY) - sD;
days = startMonthRestDays + eD - 0;
}
var lastMonth = eM - 1;
var yearForEndMonthDays = eY;
if (lastMonth < 1) {
lastMonth = 12;
yearForEndMonthDays = eY - 1;
}
var endMonthDays = getMonthdays(lastMonth, yearForEndMonthDays);
if (days >= endMonthDays) {
months = months + 1;
days = days - endMonthDays - 1;
}
if (months >= 12) {
years = years + 1;
months = months - 12;
}
returnObject.years = years;
returnObject.months = months;
returnObject.days = days;
}
return returnObject;
}
function main() {
var difference = getTimeDifferenceContract("30.09.2014", "01.10.2015");
var years = difference.years;
var months = difference.months;
var days = difference.days;
jQuery('#myText').text(years + " years, " + months + " months, " + days + " days");
}
main();
Fiddle: http://jsfiddle.net/4ddL27gx/2/
Any ideas to solve this?
I hope this will help:
Obtain difference between two dates in years, months, days in JavaScript
i was having the same necessity but no answer so i wrote a functions that seems to work...
i have used moment to achieve the result you need
var moment1 = new moment(new Date("30/Sep/2014"));
var moment2 = new moment(new Date("01/Oct/2015"));
var diffInMilliSeconds = moment2.diff(moment1);
var duration = moment.duration(diffInMilliSeconds);
var years = duration.years();
var months = duration.months();
var days = duration.days();
$('.div1').text(moment1.format());
$('.div2').text(moment2.format());
$('.div3').text(years + " years, " + months + " months, " + days + " days");
jsfiddle http://jsfiddle.net/mfarouk/qLqm3uuh/1/
i am trying to do a javascript program and calculate the age for the use, i have done the code below,
function submitForm() {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var days = d.getDay();
var minutes = d.getMinutes();
var hours = d.getHours();
var byear = document.dataform.year.selectedIndex;
var bmonth = document.dataform.month.selectedIndex;
var bday = document.dataform.day.selectedIndex;
var bhours = bday * 24;
var bmin = 60 * b hours;
var dyears = year - byear;
var dmonth = month - bmonth;
var ddays = (days - bday);
var dhours = hours - bhours;
var dminutes = minutes - bmin;
var daysTillBDay = 365 - bday;
if (isLeapYear() == true) {
dyears = year - byear;
dmonth = month - bmonth;
ddays = (days - bday) + 1;
dhours = hours - bhours;
dminutes = minutes - bmin;
daysTillBDay = 365 - bday;
}
var el = document.getElementsByName('uyears');
el[0].value = dyears + " years old.";
el = document.getElementsByName('umonths');
el[0].value = dmonth + " months old.";
document.getElementsByName('udays')[0].value = ddays;
document.getElementsByName('lmonths')[0].value = dmonth;
document.getElementsByName('ldays')[0].value = ddays;
document.getElementsByName('lhrs')[0].value = dhours;
document.getElementsByName('lmin')[0].value = dminutes;
document.getElementsByName('bdays')[0].value = daysTillBDay + " days left till your birthday.";
}
I think i will be work before i try to run the program, after i run the program, i found that the program give me almost everthing wrong, i have the year like 2013(newest yrs.), and the month i will equal the negativetive number such as -1 if i enter 11. I just try to find users age, which i believe is the date of today(today's gate)-(the birthday date), but is not workng now, anyobne know what>?
The problem is very simple (and one mistake that I've made myself) - new Date().getDay() returns the day in the week (0 for Monday, through to 6 for Sunday), not the day in the month.
The function that you're looking for is new Date().getDate(), which returns 1 for January the 1st, 25 on Christmas Day, and so on.
In my form I have a datafield where I select the day of the week!
For example if I select today 23-03-2012 Friday, I need to get an array of days from previous Monday to this next Saturday.
array:
[0],[19-03-2012],[Monday]
[1],[20-03-2012],[Monday]
[2],[21-03-2012],[Wednesday]
[3],[22-03-2012],[Monday]
[4],[23-03-2012],[Friday]
[5],[24-03-2012],[Saturday]
How can i do it for any selected day of the week obviously paying attention to changes?
Thanks
This function will return an array of all the dates in the week of date, Monday to Saturday.
function GetDaysOfWeek(date)
{
var days = new Array();
for (var i = 0; i < 6; i++)
{
days[i] = new Date(date.getYear(),
date.getMonth(),
date.getDate() - date.getDay() + 1 + i);
}
return days;
}
mayby try out MomentJs: http://momentjs.com/docs/
some examples:
moment().day(-7); // set to last Sunday (0 - 7)
moment().day(7); // set to next Sunday (0 + 7)
moment().day(10); // set to next Wednesday (3 + 7)
moment().day(24); // set to 3 Wednesdays from now (3 + 7 + 7 + 7)
For display the current day of the week:
var now = new Date();
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.write("Today is " + dayNames[now.getDay()] + ".");
First find todays date
Find the last monday (including today)
Show that date, and the next 5 days after it (Tuesday-Saturday)
var d = new Date();
if (d.getDay()==0){
d.setDate(d.getDate() + 1);
}
​while (d.getDay() != 1){
d.setDate(d.getDate() - 1);
}
var days = new Array();
for (var i = 0; i < 6; i++){
days[i] = d.getDate() + i;
}
return days;
try this :
var dayString = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var now = new Date();
var currentDay = now.getDay(); // return 0 for Sunday, 6 for Saturday
var result = [];
var tempDate = new Date(now.getTime());
tempDate.setDate(now.getDate()-(currentDay+6)%7); // now tempDate is previous Monday
while(tempDate.getDay()!=0) {
var currentMonth = tempDate.getMonth()+1;
if(currentMonth<10) currentMonth = "0"+currentMonth;
result.push([tempDate.getDay()-1,tempDate.getDate()+"-"+currentMonth+"-"+tempDate.getFullYear(),dayString[tempDate.getDay()]]);
tempDate.setDate(tempDate.getDate()+1);
}
console.log(result);
Something like the following will do the trick, I"m sure you can get the formatting to where you want it.
// Assuming d is a date object
function getDateArray(din) {
// Add leading zero to one digit numbers
function aZ(n){return (n<10? '0':'') + n;}
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var d = new Date(din); // Don't wreck input date
var dn = d.getDay();
var a = [];
var i = 6; // length of day array
if (!dn) {
// It's Sunday, what now?
return ['Sunday!'];
}
d.setDate(d.getDate() + 6 - dn); // Next Saturday
do {
a[i--] = i + ' ' + aZ(d.getDate()) +
'-' + aZ(d.getMonth() + 1) +
'-' + d.getFullYear() +
' ' + days[d.getDay()];
d.setDate(d.getDate() - 1);
} while (i);
return a;
}
// Test it
var date = new Date(2012,2,2)
alert( date + '\n\n' + getDateArray(date).join('\n'));
/*
Fri Mar 02 2012 00:00:00
0 27-02-2012 Monday
1 28-02-2012 Tuesday
2 29-02-2012 Wednesday
3 01-03-2012 Thursday
4 02-03-2012 Friday
5 03-03-2012 Saturday
*/