Javascript add days to a existing calendar object off by one month - javascript

I'm trying to read a date from a Calendar object and add a specific amount of days to it (i.e. 7)
Here is the code that I have:
var daysFromBeginDate = parseInt($("#policyDuration").val()) * 7
alert(daysFromBeginDate)
var beginDate = new Date("2015-04-24");
alert(beginDate)
var endDate = new Date("2015-05-08");
alert(beginDate.getDate() + daysFromBeginDate)
endDate.setDate(new Date(beginDate.getDate() + daysFromBeginDate));
alert(endDate.toString())
and I am getting Sun May 31 2015 17:00:000 GMT as my answer. It should be that with one less month, where is the extra month getting added?

JavaScript using the below call, I found out that the month argument counts starting from zero.
new Date(2015, 3, 1); // that's the 1st April 2015!
And what is causing the issue is the below code snippet in your code:-
endDate.getMonth() + 1
That is possibly the reason for your issue..
EDIT:
if the below code
var endDate = new Date("2015-05-08");
is changed to
var endDate = new Date();
you will get correct output..
it is because setDate sets the day of the month and April has only 30 days so it is rolled over and you get it as May and you get 31 because 24+7 is 31..

Related

Google script add row with date only on certain dates

I am trying to make a Google Sheet that automatically adds new rows with a weekday date in the first columns, two days before the respective date (Mondays get added on Saturday, Tuesdays on Sunday, etc.). For this I have written the following function:
function addRowsWithDate() {
var ss = SpreadsheetApp.getActiveSheet();
var Today = new Date();
Today.setDate(Today.getDate()+0); // I am using this to experiment with different dates
var newDate = new Date();
var dayOfWeek = Today.getDay();
if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
newDate.setDate(Today.getDate()+2);
ss.insertRowsBefore(1, 1); // Add new rows
ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow
}
}
This works as expected if I leave the +0 as it is, or comment out that line, but once I start changing that value to experiment with what will happen when I run this code on different dates I returns dates in other months. For example, offsetting today to +3 (as of 31 September) adds a row with 5 September. Now that I am typing this I see the issue is possibly with getDate() returning the day of the month instead of the week like I read here. Is that correct? And if so, is there another function that returns the day of the week in Google Sheets scripts?
EDIT: it seems to be some wrapping issue. When I set +3 it returns 5 September instead of 5 October and if I set -30 I get 3 October again.
Instead of creating a new Date() for newDate, define newDate as new Date(Today) and then add 2 days to it inside the if loop.
Solution:
function addRowsWithDate() {
var ss = SpreadsheetApp.getActiveSheet();
var Today = new Date();
Today.setDate(Today.getDate()+3); // I am using this to experiment with different dates
var newDate = new Date(Today);
var dayOfWeek = Today.getDay();
if (dayOfWeek<=3 || dayOfWeek==6){ // On Saturday through Wednesday
newDate.setDate(newDate.getDate()+2);
ss.insertRowsBefore(1, 1); // Add new rows
ss.getRange(1, 1).setValue(newDate); // Set date to the day after tomorrow
ss.getRange(1, 2).setValue(Today);
}
}

Javascript and setMonth behaving unexpectedly

I am doing datObj.setMonth(1), but the month is being set to March? Isn't 1 supposed to be February? I'm using Chrome 79.
Here's part of code meant to parse dates such as YYYY-MM-DD HH:MM:SS (because safari can't do that natively)
var date = "2020-02-02 23:59:00"
if (typeof date == 'string')
{
var dateParts = date.split(/[:-\s]+/);
if (dateParts.length == 6)
{
dateObj = new Date();
dateObj.setYear(dateParts[0]);
var m = dateParts[1] - 1;
console.log('m= ' + m);
dateObj.setMonth(m);
console.log('after setmonth, date= ' + dateObj);
dateObj.setDate(dateParts[2]);
dateObj.setHours(dateParts[3]);
dateObj.setMinutes(dateParts[4]);
dateObj.setSeconds(dateParts[5]);
}
}
console.log(dateObj);
alert(dateObj);
Your problem, as you figured, is that you're setting the month while the day is still 30. While you could work around that by using setFullYear and pass year, month and day at once, you really should just construct the whole Date object with the right values in the first place:
dateObj = new Date(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);
or rather using UTC as the timezone:
dateObj = new Date(Date.UTC(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]));
Just figured this out before I submitted. Today is January 30th, 2020. I can't change the month to February, because there is no February 30th. So, the code breaks either on the 29th or the 30th day of the month.
In JavaScript, it is advisable to do
dateObj.setMonth(monthNum -1, dayNum)
to set the day and month at the same time to avoid this problem

Set custom start date in html

I would like to set a custom start date for a calendar. So instead of the Gregorian calendar's start at 0, 2016 years ago. I would like to start at something like 1980 and a custom month and day too.
So instead of a new year at January 1st, I would like November 5th to be the new year instead (but it's still called January 1st, but compared to the Gregorian calendar, it's November 5th).
Which means, when we (with the Gregorian calendar) have the date 2016-02-10, the calendar I make, I would like it to be year 36 (2016-1980), month April (as November is now first instead of January according to the Gregorian calendar), and day 15 (10+5). So 2016-02-10 would be 30-04-15.
I have this code, but I don't know how to get it to work. Is it possible to do or will I have write code for everything that can happen?
<script type="text/javascript">
var tmonth=new Array("November","December","January","February","March","April","May","June","July","August","September","October");
function GetClock(){
var d=new Date();
//d.setFullYear(1980,0,3);
var nmonth=d.getMonth()
ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
nyear-=1962;
d.setFullYear(nyear,nmonth,ndate);
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;
if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}
if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;
document.getElementById('clockbox').innerHTML=""+tmonth[nmonth]+" "+ndate+", "+nyear+" "+nhour+":"+nmin+":"+nsec+ap+"";
}
window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
<div id="clockbox"></div>
If i was going to do something like this i'd probably get the difference between now and November the 5th (last year) in milliseconds which is: 8592904550
This means, you can subtract that number from the current timestamp to get the date that amount of seconds ago. I'd then take the current year and -1980 to get the year number.
$(function(){
var el = $('.clockbox');
var dateNow = new Date();
var newDateStamp = dateNow-8592904550;
var newDate = new Date(newDateStamp);
el.text(newDate.getMonth()+1 + "-" + newDate.getDate() + "-" + (dateNow.getFullYear()-1980));
})
You can see a fiddle using jQuery here: https://jsfiddle.net/fpmes8y3/1/
remember the getMonth is zero indexed so you need to +1 to get the true number.
Sorry if i've misunderstood your question.

Does this code work fine? I'd like to get the timestamp of the following date

I'm building a chrome extension now.
I'd like to set an alarm to be fired at 23:59:59 everyday, so I can reset some saved settings at the end of day.
I wrote this code below but, I'm not used to using Date Object.
And I'm worried if this code works fine and don't mess up everything.
Especially, I'm worried about the code for setting up an alarm again for the next day.
var day = now.getDate() + 1;
To get the date of the following day, I just add 1 to the returned value of "now.getDate()".
But, I wonder if the returned value of "now.getDate()" is the end of the month and because of that, adding 1 ends up getting the date which doesn't exist.
Please take a look at my code and tell me if this works fine or not.
Thank you in advance!!
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var timestamp = Number(new Date(year, month, day, 23, 59, 59, 0));
//set an alarm for today at 23:59:59.
chrome.alarms.create('resetSpentTime', {
when: timestamp
});
// when alarm fires, do the following.
chrome.alarms.onAlarm.addListener(function() {
//clear some saved settings at the end of day.
//After that, set an alarm again for tomorrow at 23:59:59.
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate() + 1;
var timestamp = Number(new Date(year, month, day, 23, 59, 59, 0));
//set an alarm for tomorrow at 23:59:59.
chrome.alarms.create('resetSpentTime', {
when: timestamp
});
})
I'll suggest use date.js Link for date.js filefor all date operations in Javascript in which you can add days or parse dates easily. See the demo on given site.
You can try this. Nextday as well as end of month is auto handeled.
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Source: Add days to JavaScript Date

how to add time plus and recalculate the datetime

i have this datetime format:
Oct 31, 2012 08:59:52
i would like to re-calculate the datetime incremented (for example) of 2 hours or 50 minutes plus how can i do that?
i need to return the same datetime format showed above and not a timestamp!
var date = new Date("Oct 31, 2012 08:59:52");
var timeInMillis = date.getTime();
Now that you have time in milliseconds, you can just add the time you want in millis.
Eg: 2 hours? So, 2*60*60*1000 + timeInMillis
var newDate = new Date(2*60*60*1000 + timeInMillis);
If you want to convert your newDate into the original format, which is a long process, you can some guidance from here:
Where can I find documentation on formatting a date in JavaScript?
My pick of the answers would be:
Use MomentJS
You could first parse this to a date:
var d=new Date("October 31, 2012 08:59:25").getTime();
Then add the offset:
d+= (seconds)*1000 + (minutes)*60000 + (hours)*3600000;
var result = new Date(d);
I am just not sure wether it accepts 'Oct' instead of 'October'
time_start = new Date(year, month, day, hours, minutes, seconds, milliseconds);
time_finish = new Date() - time_start;
Set the Date using the format listed above. To calculate the interval between two points of time, just subtract the current date from the past date.

Categories

Resources