Working with Javascript dates, getting 0 or above 31 - javascript

I am using this code to generate 5 dates for my 'calendar' from the current week:
var days = new Array(4);
GetDaysOfWeek(new Date());
function GetDaysOfWeek(date)
{
for (var i = 0; i < 5; i++)
{
var $dd = (date.getDate() - date.getDay() + 1 + i);
var $mm = date.getMonth()+1;
var $yyyy = date.getFullYear();
if($dd<10){$dd='0'+$dd}if($mm<10){$mm='0'+$mm}
days[i] = $dd+'/'+$mm+'/'+$yyyy;
}
}
However depending what date it is it can return 00/10/2013 or 32/10/2013 on some of my boxes. It seems the only one updating correct is the actual date I am on.
How would I update those 5 dates so I would get the correct dates instead of non exist dates.
Thanks in advance.

currentTimestamp = new Date().getTime()
currentDay = currentTimestamp-currentTimestamp%(24*60*60*1000)
for (var i = 1; i< 6; i++){
nextDay = new Date(currentDay + i*24*60*60*1000)
days[i] = nextDay.toString(); //specify the format yourself
}

Here's a somewhat shorter way of creating an array of the dates of 5 weekdays from a given date;
function weekdays(d){
// set date [d] (or today) to the sunday before
var d = (function(){
this.setDate(this.getDate()-(this.getDay()));
return this;
}).apply(d || new Date);
// create an Array with length 5 and map 5 dates starting
// from date [d] into it
return String(Array(5)).split(',')
.map(function(){
return new Date(this.setDate(this.getDate()+1));
}, d);
}
It returns the weekdays from the first monday before the date, or, if the given date is a sunday, the dates of the weekdays from the next week.
weekdays();
//=> [Mon Oct 21 2013 17:14:23 GMT+0200, ... ,Fri Oct 25 2013 17:14:23 GMT+0200]
weekdays(new Date('2013/10/06'));
//=> [Mon Oct 07 2013 00:00:00 GMT+0200, ..., Fri Oct 11 2013 00:00:00 GMT+0200]
See also: Mozilla DN on map
Maybe this jsfiddle is of use to you?

Related

How to subtract 5 days from a defined date - Google App Script

I'm trying to write a script to subtract 5 days from a defined date but seems not working, here's my code:
var End_Day = sheet.getRange(i + 2, 20).getValue();
Logger.log(End_Day);
var End_day_2 = new Date();
End_day_2.setDate(End_Day.getDate()-5);
Logger.log(End_day_2);
and the result is not just - 5 days:
11:18:47 AM Info Sat Jun 04 00:00:00 GMT+08:00 2022
11:18:47 AM Info Fri Apr 29 11:18:47 GMT+08:00 2022
I am quite confused why the date move from Jun to Apr.
Thanks for having a look
Try:
var End_Day = sheet.getRange(i + 2, 20).getValue();
var End_day_2 = new Date(End_Day.getTime() - (5 * (1000 * 60 * 60 * 24)))
Logger.log(End_Day);
Logger.log(End_day_2);
Function:
const endDay = sheet.getRange(i + 2, 20).getValue()
const endDay2 = DateFromDaysAgo(endDay, 5)
...
function DateFromDaysAgo(startDate, number) {
if (typeof startDate === `string`) { startDate = new Date(startDate) }
return new Date(startDate.getTime() - (number * (1000 * 60 * 60 * 24)))
}
You should learn more about Date.prototype.setDate().It only changes the day of the month of a given Date instance.
As the code you posted, the day of the month of End_Day is 4, End_day_2.setDate(4 - 5) equals to End_day_2.setDate(-1) and the month of End_day_2 is April according to the console result, because there're 30 days in April, setDate(-1) means setDate(29), so you got Apr 29 at the end. That's how it goes.
One right way to do is substracting 5 days worth of milliseconds.
function addDays(date, days){
const DAY_IN_MILLISECONDS = 24 * 60 * 60000;
return new Date(date.getTime() + days * DAY_IN_MILLISECONDS);
}
console.log(addDays(new Date(), -5).toString()); // 5 days ago
I am quite confused why the date move from Jun to Apr.
It's because you're setting date on today(End_day_2) and not on your predefined date(End_day).
Change
End_day_2.setDate(End_Day.getDate()-5);
to
End_Day.setDate(End_Day.getDate()-5);
console.info(End_Day);
If what's coming from the sheet is a string, you will have to convert the date string into a date object.
The other thing is you have to work in milliseconds as #vanowm says:
606024*5 = 432000 * 1000 = 432000000
so skipping the sheet entirely:
x = new Date
> Fri May 27 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
y = new Date(x - 432000000)
> Sun May 22 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
This will do the trick. Works with any date and can subtract any number of days
const subtractDays = (fromDate, numDays) => {
if (!(fromDate instanceof Date)) throw 'The first argument must be a date';
return new Date(new Date().setDate(fromDate.getDate() - +numDays));
};
Weekago
function weekago() {
let dt = new Date();
dt.setDate(dt.getDate()-7);
Logger.log(dt);
return dt;
}
Five days ago
function fiveago() {
let dt = new Date();
dt.setDate(dt.getDate()-5)
Logger.log(dt);
return dt;
}
Five days from a date in a spreadsheet cell
function fivefromadateinspreadsheet() {
const v = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
let dt = new Date(v);
dt.setDate(dt.getDate()-5);//Note that does not return a date it return the numbrer of milliseconds
Logger.log(dt);
return dt;
}
You can subtract 5 days from a defined date in Google App Script by using the Utilities.formatDate() method. Here's an example:
function subtractDays() {
var date = new Date();
var subtractDays = 5;
// Subtract 5 days from the current date
date.setDate(date.getDate() - subtractDays);
// Format the new date
var newDate = Utilities.formatDate(date, "UTC", "yyyy-MM-dd");
Logger.log(newDate);
}
In this example, we first create a Date object to represent the current date. Then, we subtract 5 days from the current date by using the setDate() method. Finally, we format the new date using the Utilities.formatDate() method and log it to the console using the Logger.log() method.
You can modify the subtractDays variable to subtract a different number of days from the date, or you can use a different date object to start with.

Adding days to a Date object in JavaScript is not working properly

I have read several questions on stack overflow and all over the internet but somehow I am unable to get it right. I get a date from another function and the value is as below.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date();
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
The output I get is:
Mon Jul 12 2021 19:00:57 GMT+1000 (Australian Eastern Standard Time)
where as this should be some date in June.
Please can someone help me understand what I am doing wrong?
The problem is that when you are initializing a new date object using new Date(), the date object is initialized with the current date. When you increment the days using currentDate.getDate() + offset the day of the month is first set to that of currentDate and incremented by offset but the month from which it is incremented is the current month. Try this one.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date("2021-04-27T15:30:27.588+0000");
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
1 day is equal to 86,400,000 milliseconds. You can multiply that value by 45 and add it to your date:
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate);
// Add 45 days
var offset = 45;
var xDate = new Date(currentDate.getTime() + offset * 86400000);
console.log(xDate);
My suggestion:
const addDays = (date, days) => {
var ndt = new Date(date);
ndt.setDate(date.getDate() + days);
return ndt;
};
var date = new Date("2021-04-27T15:30:27.588+0000");
console.log(date);
console.log(addDays(date, 45));
I agree Wais Kamal's answer is right. The below code is more succinct since you avoid time calculations
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
var offset = 45;
var xDate = currentDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
You can make use of the moment here. Link to official docs. Don't forget to install moment package like so (assuming you are using npm)
npm i moment
const myDate = "2021-04-27T15:30:27.588+0000";
const updatedDate = moment
.utc(myDate)
.add(45, 'days')
.format('YYYY-MM-DD');
console.log('updatedDate', updatedDate); // "2021-06-11"

How to check if last day of month is on friday Javascript

I'm supposed to write a code for codewars to find out the number of times a month ends with a Friday within a range of years.
To start off, I did research and found out several solutions but I still couldn't figure out the results in the console.log.
The first solution is from this tutorial:
In this code, the solution is
let LastDay = new Date(1998, 5 + 1, 0).getDate();
I was able to get the date, but it wasn't clear which day the date falls upon.
Then I found another solution at w3schools. This solution also set the date to be the last day of this month:
var d = new Date();
d.setMonth(d.getMonth() +1, 0);
document.getElementById("demo").innerHTML = d;
However, it works if it displays it as innerHTML = Sat Nov 30 2019 00:57:09 GMT-0500 (Eastern Standard Time). However, when I tried to rewrite the code and console.log it like in this example:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(lastday);
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting. I thought that if it does display the dates, starting with the day, I can convert the date to string or array and check if the first element is Friday and then add it to the counter in the code I'm writing. How do I get the code to display the way I want it to.
something like this will work...
function LastDayOfMonth(Year, Month) {
return new Date((new Date(Year, Month, 1)) - 1);
}
var d = LastDayOfMonth(new Date().getYear(), new Date().getMonth())
//var d = LastDayOfMonth(2009, 11)
var dayName = d.toString().split(' ')[0];
console.log(dayName)
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting
Because you console.log the output of the setMonth method, not the date object:
let lastday = d.setMonth(month, 0);
console.log(lastday);
According to the documentation, the setMonth method returns:
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Instead you should use that output to create a new instance of the date object:
let lastday = new Date(d.setMonth(month, 0));
console.log(lastday);
Algorithms to get the last day of the month are generally based on setting a date to day 0 of the following month, which ends up being the last day of the required month.
E.g. to get the last day for June, 2019 (noting that 6 is July, not June):
let endOfJune = new Date(2019, 6, 0):
Once you have the date, you can get the day where 0 is Sunday, 1 is Monday, etc. and 5 is Friday:
let endOfJuneDay = endOfJune.getDay();
The set* methods modify the Date they're called on and return the time value for the modified date. So you don't need to assign the result to anything:
let d = new Date();
let month = d.getMonth() + 1;
// Set date to the new month
d.setMonth(month, 0);
console.log(d);
So if you want to loop over the months for a range of years and get the number that end with a Friday (or any particular day), you might loop over the months something like:
/*
** #param {number} startYear - start year of range
** #param {number} endYear - end year of range
** #param {number} dat - day number, 0 = Sunday, 1 = Monday, etc.
** default is 0 (Sunday)
*/
function countEOMDay(startYear, endYear, day = 0) {
// startYear must be <= end year
if (startYear > endYear) return;
// Start on 31 Jan of start year
let start = new Date(startYear, 0, 31);
// End on 31 Dec of end year
let end = new Date(endYear, 11, 31);
let count = 0;
// Loop over months from start to end
while (start <= end) {
// Count matching days
if (start.getDay() == day) {
++count;
}
// Increment month to end of next month
start.setMonth(start.getMonth() + 2, 0);
}
return count;
}
console.log(countEOMDay(2019, 2019, 5)); // 1
console.log(countEOMDay(2018, 2019, 5)); // 3
You can use setMonth() method to set the month of a date object. The return value of setMonth() method is milliseconds between the date object and midnight January 1 1970. That's what you get from console.log(lastday);
Your return value,
1575093343211
is milliseconds between your date object (d) and midnight January 1 1970.
If you want to get the expected date, you have to console log your date object instead the lastday, as follows:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(d);
output: Sat Nov 30 2019 00:02:47 GMT+0530 (India Standard Time)
This is an alternative solution I wrote to solve your problem. This will return the number of times a month ends with a Friday within a range of years. Hope this will help you :)
var days = [];
var count = 0;
function getLastFridaysCount(startYear, endYear) {
for (var year = startYear; year <= endYear; year++) {
days = [
31,
0 === year % 4 && 0 !== year % 100 || 0 === year % 400 ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
];
for (var month = 0; month <= 11; month++) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(days[month]);
if(myDate.getDay() == 5)
{
count++;
}
}
}
return count;
}
console.log("count", getLastFridaysCount(2014, 2017));
this is the solution, in the code can find the comments "//" explaining of what happens in each iteration.
function lastDayIsFriday(initialYear, endYear) {
let count = 0;
//according to when the year ends starts the loop
if (endYear !== undefined) {
let start = new Date(initialYear, 0, 31);
let end = new Date(endYear, 11, 31);
while(start <= end) { //check if the start date is < or = to the end
//The getDay() method returns the day of the week (from 0 to 6) for the specified date.
if(start.getDay() === 5) { //if = to FriYAY!!!
count++; //count the day
}
start.setMonth(start.getMonth()+2, 0);// returns the month (from 0 to 11) .getMonth
} //& sets the month of a date object .setMonth
return count;
} else {
let start = new Date(initialYear, 0, 31);
console.log(start.toString());
for(let i = 0; i < 12; i++) {
if(start.getDay() === 5) {
count++;
}
start.setMonth(start.getMonth() + 2, 0);
// console.log(start.toString());
}
return count;
}
}

getDate returning the next day on current time

Is this due to the time zones settings on my laptop or is it something more complex?
Current time
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var week = 7;
console.log ('date ',dateObj,' day is ',day);
output
> date Mon Jan 14 2019 23:05:35 GMT-0500 (Eastern Standard Time) day is 15
edit: that the time that new Date() created (Mon Jan 14 2019 23:05:35 GMT-0500) is in fact the correct time I am after.
after considering the information I read in comments, it seems I need to subtract the hourly change ( - 5 ) to get the EST, which seems to be what I'm after.
it seems I need to subtract the hourly change ( - 5 ) to get the EST
Subtracting 5 is not a good idea, as it doesn't account for daylight savings.
I'd suggest using toLocaleString() to be safe.
var dateObj = new Date();
//Output as UTC
var utc = { timeZone: "UTC" };
console.log(dateObj.toLocaleString("en-US", utc));
//Output as EST
var est = { timeZone: "America/New_York" };
console.log(dateObj.toLocaleString("en-US", est));
You need to keep timezones consistent. Change this:
console.log ('date ',dateObj,' day is ',day);
To this:
console.log ('date ',dateObj.getUTCDate(),' day is ',day);
And it will work:
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var week = 7;
console.log('date ', dateObj.getUTCDate(), ' day is ', day);

How to list all month between 2 dates with moment.js?

I've two dates
2015-3-30 2013-8-31
How can I make a month list like:
[ '2015-3', '2015-2', '2015-1', '2014-12', '2014-11', '2014-10', '2014-09', '2014-08', '2014-07', '2014-06', '2014-05'....., '2013-08' ]
Thanks.
This should do it:
var startDate = moment('2021-12-31');
var endDate = moment('2022-12-14');
var betweenMonths = [];
if (startDate < endDate){
var date = startDate.startOf('month');
while (date < endDate.endOf('month')) {
betweenMonths.push(date.format('YYYY-MM'));
date.add(1,'month');
}
}
I think the original answer isn't entirely correct, as you wouldn't get '2015-3' in your array. This is due to the fact your start date would eventually end up as '2015-3-31' and would fail the conditional in place. You could extend it like below.
UPDATE: I've now included cloning the dateStart variable so it isn't mutated at all.
var dateStart = moment('2013-8-31');
var dateEnd = moment('2015-3-30');
var interim = dateStart.clone();
var timeValues = [];
while (dateEnd > interim || interim.format('M') === dateEnd.format('M')) {
timeValues.push(interim.format('YYYY-MM'));
interim.add(1,'month');
}
You could try with this example
var one = moment("2015-3-30");
var two = moment("2014-8-31");
var dateDiffs = [];
var count = Math.round(moment.duration(one.diff(two)).asMonths());
month = two.month() + 1;
year = two.year();
for (var i=1; i<=count; i++) {
if (month > 12) {
month = 1;
year++;
}
dateDiffs.push(year+"-"+month);
console.log(month);
month++;
}
console.log(dateDiffs);
You are using multiple formats in the output: YYYY-MM and YYYY-M, so I picked the first. You can edit as you see fit.
var startDateString = "2012-5-30";
var endDateString = "2015-8-31";
var startDate = moment(startDateString, "YYYY-M-DD");
var endDate = moment(endDateString, "YYYY-M-DD").endOf("month");
var allMonthsInPeriod = [];
while (startDate.isBefore(endDate)) {
allMonthsInPeriod.push(startDate.format("YYYY-MM"));
startDate = startDate.add(1, "month");
};
console.log(allMonthsInPeriod);
document.getElementById("result").innerHTML = allMonthsInPeriod.join("<br />");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<div id="result"></div>
const getMonths = (start, end) =>
Array.from({ length: end.diff(start, 'month') + 1 }).map((_, index) =>
moment(start).add(index, 'month').format('MM.YYYY'),
);
const months = getMonths(moment('01.2019','MM.YYYY'),moment('01.2020','MM.YYYY'))
console.log(months)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
This is the best way in my opinion.
const startDate = moment('2013-8-31', 'YYYY-M-DD');
const endDate = moment('2015-3-30', 'YYYY-M-DD');
const months = [];
const flag = startDate;
while (flag.diff(endDate) <= 0) {
months.push(flag.format('YYYY-M'));
flag.add(1, 'M');
}
Why don't you just https://date-fns.org/v2.13.0/docs/eachMonthOfInterval ??
// Each month between 6 February 2014 and 10 August 2014:
var result = eachMonthOfInterval({
start: new Date(2014, 1, 6),
end: new Date(2014, 7, 10)
})
//=> [
// Sat Feb 01 2014 00:00:00,
// Sat Mar 01 2014 00:00:00,
// Tue Apr 01 2014 00:00:00,
// Thu May 01 2014 00:00:00,
// Sun Jun 01 2014 00:00:00,
// Tue Jul 01 2014 00:00:00,
// Fri Aug 01 2014 00:00:00
// ]

Categories