Getting names of past days (ex: 7 days ago, 8 days ago ...) - javascript

I am trying to find names of past days. I'm using this script to get names of past 7 days successfully, however, it doesn't work if I increase the past days, for example 7 days ago, 8 days ago or more.
var dayOfWeek = new Array();
dayOfWeek[0] = "Sun";
dayOfWeek[1] = "Mon";
dayOfWeek[2] = "Tue";
dayOfWeek[3] = "Wed";
dayOfWeek[4] = "Thu";
dayOfWeek[5] = "Fri";
dayOfWeek[6] = "Sat";
var myDate = new Date();
myDate.setDate(myDate.getDate());
var myDate1 = new Date();
myDate1.setDate(myDate1.getDate() - 1);
var myDate2 = new Date();
myDate2.setDate(myDate2.getDate() - 2);
var myDate3 = new Date();
myDate3.setDate(myDate3.getDate() - 3);
var myDate4 = new Date();
myDate4.setDate(myDate4.getDate() - 4);
var myDate5 = new Date();
myDate5.setDate(myDate5.getDate() - 5);
var myDate6 = new Date();
myDate6.setDate(myDate6.getDate() - 6);
var on1 = dayOfWeek[myDate.getDay()];
var on2 = dayOfWeek[myDate1.getDay()];
var on3 = dayOfWeek[myDate2.getDay()];
var on4 = dayOfWeek[myDate3.getDay()];
var on5 = dayOfWeek[myDate4.getDay()];
var on6 = dayOfWeek[myDate5.getDay()];
document.write(on5);
What is the correct way to do that ?

If I understand you correctly, you're trying to do something like (assuming today is Wednesday):
2 days ago was Monday
5 days ago was Friday
8 days ago was Tuesday
If this is correct, then this should do it:
function getDayOfWeekAgo(daysAgo) {
var today = new Date().getDay(),
days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
today = (today+daysAgo*6)%7; // adding 6 per day is the same as subtracting one
// due to the modulo, just without the complications
// that negative numbers would bring
return days[today];
}
Or, more efficiently:
window.getDayOfWeekAgo = (function() {
var today = new Date().getDay(),
days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
return function(daysAgo) {return days[(today+daysAgo*6)%7];}
})();

Related

days left until user's bday

I've created a pirate speak program.
It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?
var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');
Ok, I have cleaned up your JavaScript a little. Best practice was to get the date from the string and parse each part then just create a Date object from there. What's easier in the future is to use a datepicker HTML component rather than a string, but I understand that wasn't your goal for this.
Next, do the plus 100 calculation and display that result.
Lastly, take the Date object we made and take the information that we need from it. FWIW getDay() returns the day of the week, you want getDate() which return the day of the month. Then calculate how many days away from those in the next year. Display that result in the console.
I think you were getting that NAN because you were doing calculations on strings not numbers or it was because there weren't enough parameters in daysUntilNext(), so you were operating on null or undefined somewhere
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var daySubstring = birthDateString.substring(3, 5);
var monthSubstring = birthDateString.substring(0, 2);
var yearSubstring = birthDateString.substring(6, 10);
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');
The other answerer's code is correct, but not clear. Here's the same, only more user-friendly.
The difference is that single-digit months or days won't bother you.
I hope I could help.
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var inputdate = birthDateString.split("/");
var daySubstring = inputdate[1];
var monthSubstring = inputdate[0];
var yearSubstring = inputdate[2];
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');

How can I add 3 years to a date using Google scripting?

I am trying to add 3 years to a date that I have extracted from a cell on a Google sheet. My coded currently looks like this:
var courseDate = values[row][col];
var courseDay = courseDate.getMonth();
var courseMonth = courseDate.getMonth();
var courseYear = courseDate.getYear();
var renewalDate = new Date(courseYear + 3, courseMonth, courseDay);
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var c = new Date(year + 3, month, day)

Find out how many days till next birthday and previous birthday - javascript [duplicate]

I tried this but it fails
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.
The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,3,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Why reinvent the wheel??
Use datejs
and after:
var startd = Date.parseExact(ind, "yyyy-MM-dd");
var endd = Date.parseExact(end, "yyyy-MM-dd");
var diff = new Date(endd - startd);
var days = diff/1000/60/60/24;
That's all folks!
The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.
The fromNow function is also super nice if want to display the number of days from now you could do something like:
moment([2014, 4, 5]).fromNow();
would produce something like "330 days" if it's 330 days away.
http://momentjs.com/docs/#/displaying/fromnow/
Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):
const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');
Simple, fast, accurate!
Here's the same code, explained:
// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';
// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');
// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');
// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');
If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.
The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.
This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.
const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);
export const daysUntilBirthday = () => {
const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
const oneDay = 24 * 60 * 60 * 1000;
const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
const firstDate = new Date();
const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
const daysOrDay = days === 1 ? 'day' : 'days';
return days !== 365 ? `${days} ${daysOrDay} until my birthday 😉😉` : '🎂 TODAY IS MY BIRTHDAY 🎂';
};

Date is considering 31 days of month

While working with date difference, when I am using below code somehow function is assuming that all the months have 31 days. For ex. if I am subtracting 01-March with 28-February the difference is coming as 4 days. Is there any simple way to twick this. Any help will be appreciated.
function myFunction()
{
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2);
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2);
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var x = document.getElementById("demo");
x.innerHTML=(n1-n)/(1000*24*60*60);
}
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
U can subtract like this--
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var days = diff*24*60*60*1000;
You code is actually subtracting March 1 from April 1, as the months in JavaScript dates are 0-based.
var sysdt = "02/28/2013";
var date1 = new Date(sysdt);
var userdt = "03/01/2013"
var date2 = new Date(userdt);
var days = (date2-date1)/(1000*24*60*60);
or subtract 1 from month in your code
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2)-1; // months are from 0 to 11
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2)-1; // months are from 0 to 11
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var days = (n1-n)/(1000*24*60*60);

Get dates for last quarter and this quarter through Javascript

I'm trying to create a report that needs to get the dates for last quarter and this quarter through Javascript. The code worked last month but in March it doesn't work. It shows last quarter as this quarter and this quarter shows as next quarter. I am using datejs in this project. Here is the code I am using:
function thisQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarterMonth = (Math.floor(month/3)*3)+1;
var year = Date.parse('today').toString('yyyy');
var quarterStartDate = (quarterMonth < 10) ? quarterMonth+'/1/' +year : quarterMonth+'/1/'+ year;
var quarterEndDate = Date.parse(quarterStartDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');
var today = Date.parse('today').toString('M/d/yyyy');
document.getElementById(from).value = quarterStartDate;
document.getElementById(to).value = quarterEndDate;
}
function lastQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarter = (Math.floor(month/3))+1;
var lastQuarter = (quarter > 1) ? quarter - 1 : lastQuarter = 4;
var year;
if (((((lastQuarter-1)*3)+1) < 10))
{
year = Date.parse('today').toString('yyyy');
}
else
{
year = Date.parse('today').add(-1).years().toString('yyyy');
}
var firstDate = ((((lastQuarter-1)*3)+1) < 10) ? (((lastQuarter-1)*3)+1) +'/1/'+ year : (((lastQuarter-1)*3)+1) +'/1/'+ year;
var lastDate = Date.parse(firstDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');
document.getElementById(from).value = firstDate;
document.getElementById(to).value = lastDate;
}
Anyone know why it's incorrect or is there an easier way?
Simple generic solution in pure JS. First calculate quarter number:
const today = new Date();
const quarter = Math.floor((today.getMonth() / 3));
Next, current quarter:
const startFullQuarter = new Date(today.getFullYear(), quarter * 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);
Previous quarter
const startFullQuarter = new Date(today.getFullYear(), quarter * 3 - 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);
Add or subtract 3's per quarter in expression new Date(today.getFullYear(), quarter * 3 - x, 1) to get future or past quarters.
if you're using moment.js this might be easier:
var quarterAdjustment= (moment().month() % 3) + 1;
var lastQuarterEndDate = moment().subtract({ months: quarterAdjustment }).endOf('month');
var lastQuarterStartDate = lastQuarterEndDate.clone().subtract({ months: 3 }).startOf('month');
conversion to date.js should be fairly easy.
Using moment.js library its very simple to get the start and end date of a particular quarter as follows:
Start date of last quarter = moment().subtract(lastQuarterNumber, 'quarter').startOf('quarter');
End date of last quarter = moment().subtract(lastQuarterNumber, 'quarter').endOf('quarter');
Start date of current quarter = moment().startOf('quarter');
End date of current quarter = moment().endOf('quarter');
On the first function change
var quarterMonth = (Math.floor(month/3)*3)+1;
with
var quarterMonth = (Math.floor((month-1)/3)*3)+1;
and on the second function
var quarter = (Math.floor(month/3))+1;
with
var quarter = (Math.floor((month-1)/3))+1;
and I think it will be fine.
And on the second function I don't see the point of
((((lastQuarter-1)*3)+1) < 10)
a simple
(lastQuarter < 4)
will do the same job
Using moment.js:
This quarter START: moment().startOf('quarter')
This quarter END: moment().endOf('quarter')
Previous quarter START: moment().subtract(1, 'quarter').startOf('quarter')
Previous quarter END: moment().subtract(1, 'quarter').endOf('quarter')
Next quarter START: moment().add(1, 'quarter').startOf('quarter')
Next quarter End: moment().add(1, 'quarter').endOf('quarter')
I have been using date-fns library for some time now. The methods it exposes can be immensely useful in solving such problems.
You can make use of addQuarter and subQuarter methods.
Code would look something like:
const lastQuarterStartDate = startOfQuarter(subQuarters(new Date(2014, 8, 1),1))
const lastQuarterEndDate = lastDayOfQuarter(subQuarters(new Date(2014, 8, 1),1))
const thisQuarterStartDate = startOfQuarter(new Date(2014, 8, 1))
const thisQuarterEndDate = lastDayOfQuarter(new Date(2014, 8, 1))
Reference: https://date-fns.org/v2.21.2/docs/addQuarters
Use this simple code to get all quarter based on january and april
Demo
Code :
// startMonth should be january or april
function setQuarter(startMonth) {
var obj = {};
if(startMonth=='january'){
obj.quarter1 = {start:moment().month(0).startOf('month'),end:moment().month(2).endOf('month')}
obj.quarter2 = {start:moment().month(3).startOf('month'),end:moment().month(5).endOf('month')}
obj.quarter3 = {start:moment().month(6).startOf('month'),end:moment().month(8).endOf('month')}
obj.quarter4 = {start:moment().month(9).startOf('month'),end:moment().month(11).endOf('month')}
console.log(obj);
return obj;
}
else if(startMonth=='april'){
obj.quarter1 = {start:moment().month(3).startOf('month'),end:moment().month(5).endOf('month')}
obj.quarter2 = {start:moment().month(6).startOf('month'),end:moment().month(8).endOf('month')}
obj.quarter3 = {start:moment().month(9).startOf('month'),end:moment().month(11).endOf('month')}
obj.quarter4 = {start:moment().month(0).startOf('month').add('years',1),end:moment().month(2).endOf('month').add('years',1)}
console.log(obj);
return obj;
}
}
setQuarter('april');
Fiddle
Using this we can get Quarter's start and end dates dynamically irrespective of start of the financial year(Quarter).
var fYearStart=new Date('2021-1-29') //Pass your financial year's start date
var q1Start=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var dummy1=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var dummy5=new Date(fYearStart.getFullYear(),fYearStart.getMonth(),1)
var q1End=new Date(dummy1.setMonth(dummy1.getMonth()+3))
var q1FinalEnd=new Date(dummy5.setMonth(dummy5.getMonth()+3))
q1FinalEnd.setSeconds(q1End.getSeconds()-1)
console.log(q1Start.toLocaleString())
console.log(q1FinalEnd.toLocaleString())
var q2Start=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var dummy2=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var dummy6=new Date(q1End.getFullYear(),q1End.getMonth(),1)
var q2End=new Date(dummy2.setMonth(dummy2.getMonth()+3))
var q2FinalEnd=new Date(dummy6.setMonth(dummy6.getMonth()+3))
q2FinalEnd.setSeconds(q2End.getSeconds()-1)
console.log(q2Start.toLocaleString())
console.log(q2FinalEnd.toLocaleString())
var q3Start=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var dummy3=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var dummy7=new Date(q2End.getFullYear(),q2End.getMonth(),1)
var q3End=new Date(dummy3.setMonth(dummy3.getMonth()+3))
var q3FinalEnd=new Date(dummy7.setMonth(dummy7.getMonth()+3))
q3FinalEnd.setSeconds(q3End.getSeconds()-1)
console.log(q3Start.toLocaleString())
console.log(q3FinalEnd.toLocaleString())
var q4Start=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var dummy4=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var dummy8=new Date(q3End.getFullYear(),q3End.getMonth(),1)
var q4End=new Date(dummy4.setMonth(dummy4.getMonth()+3))
var q4FinalEnd=new Date(dummy8.setMonth(dummy8.getMonth()+3))
q4FinalEnd.setSeconds(q4End.getSeconds()-1)
console.log(q4Start.toLocaleString())
console.log(q4FinalEnd.toLocaleString())

Categories

Resources