I am trying to implement previous/next two weeks to my scheduler, but it is not working correctly.. This is what I try:
this.datesArray = [];
const currentDate: Date = new Date(this.startDate);
const lastDate: Date = new Date(this.endDate);
currentDate.setDate(currentDate.getDate() - 14);
lastDate.setDate(currentDate.getDate() + 30);
while (currentDate < lastDate) {
// var newDate: Date = new Date(currentDate);
this.datesArray.push(currentDate.toDateString());
currentDate.setDate(currentDate.getDate() + 1);
}
Every click I trigger this code, but there is the following issue. First 2 times it works great, but 3rd time I click next, last date.SetDate bugs out, it addds 60 days instead of 30. Here is what I mean for the previous week:
It shows current date Feb 22, but then adds 30 days, and it shows Apr 21 somehow..
Anyone had similar issues?
Related
I am doing a react project.I want to display today's date and time as "9 am" .This has to be remained unchanged till time is 9 am on next day. After that it should display time as 9 am along with date of that day and continue this till next day 9 am and so on.
<span>Last Updated: {moment().format('MMMM Do YYYY,') + " 9:00 am"}</span>
The above code displays the time as 9 am even before the time is 9 am on the nextday. It should look like current time and date gets updated only at 9 am everyday.
This code creates a function that retrieves the formatted date at a given hour. If the hour is not specified, it will use the current hour. It will return today's date, unless the hour is before 9, in which case it will return yesterday's date. The format will use the current user's native formatting for a "long" date. The HTML shows the desired result, the console logs what happens before 9 on the current day, and the current hour. The hour is determined by the user's time zone.
function getDateAtNine(forceHour) {
let now = new Date();
const hour = forceHour == null ? now.getHours() : forceHour;
if (hour < 9) {
now = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
}
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long'
}).format(now);
}
console.log(getDateAtNine(8)); // shows what will print at 8 am on today's date
console.log(getDateAtNine()); // shows what will print at the current hour on today's date
document.querySelector('#dateat9').textContent = getDateAtNine();
<span id="dateat9"></span><span id="nineam">, 9:00 am</span>
Is that what you are looking for? ;)
const getLastStartOfDay = (startOfDayHour) => {
let todayStartOfDay = new Date();
todayStartOfDay.setHours(startOfDayHour, 0, 0, 0);
let yesterdayStartOfDay = new Date(todayStartOfDay);
yesterdayStartOfDay.setDate(yesterdayStartOfDay.getDate() - 1);
let dt = new Date();
const displayDate =
dt.getHours() < startOfDayHour ? yesterdayStartOfDay : todayStartOfDay;
return displayDate;
};
console.log("LastStartOfDay: ", getLastStartOfDay(9));
I have a sheet with a time trigger set to run every 30 minutes. When the trigger happens a function is executed which will add a new row at the bottom of the sheet with some data.
On column A I have dates.
Now the problem is sometimes the Google's trigger tool by error will execute like 3 times in a row or more with less then a minute in between each execution. This happens more often than I'd like and I need a way to fix this.
I wrote some code which supposedly will delete the new recorded row if the difference between this last row and the second last row, or previous row, is less than 30 minutes. This way all the rows will always be 30 minutes apart from each other.
I'm stuck at this point where I can't figure out a way of making Google Script to compare 2 dates and return TRUE or FALSE based on my condition, which is to check if the difference between 2 dates is more/equal or less than 30 minutes, and if it is less to delete the row, otherwise do nothing. Actually I gave the condition a margin of 1 minutes because the triggers are not 100% exact and don't always happen at the same second.
The variable timerDifference returns NaN.
I suspect it might be because of the date format?
This is my code ATM:
function deleteTriggerError() {
let logSheetName = "LOG";
let logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetName);
let lastRowTimer = logSheet.getRange(logSheet.getLastRow(), 1).getValue();
let secondLastRowTimer = logSheet.getRange(logSheet.getLastRow() - 1, 1).getValue();
console.log(lastRowTimer);
console.log(secondLastRowTimer);
let dysLast = Utilities.formatDate(lastRowTimer, timeZone, 'dd/mm/yyyy hh:mm:ss');
let dysSecondLast = Utilities.formatDate(secondLastRowTimer, timeZone, 'dd/mm/yyyy hh:mm:ss');
console.log(dysSecondLast);
console.log(dysLast);
let timerDifference = dysLast - dysSecondLast;
console.log(timerDifference);
let timerDifLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetName).getRange("H3");
let timerDifLimitValueTXT = timerDifLimitRange.getValue();
let timerDifLimitValue;
//console.log(timerDifference);
timerDifLimitValue = timerDifLimitValueTXT.replace("3 0 M I N U T E S", 30 - 1);
logSheet.appendRow([""]);
if (timerDifference < timerDifLimitValue) {
logSheet.deleteRow(logSheet.getLastRow());
// console.log("TRUE");
} else {
// console.log("FALSE");
}
}
I tried the solution I saw here:
Time difference between two time showing wrong values in js
var diff = Math.abs(new Date('01/23/2020 06:30 PM') - new Date('01/23/2020 05:00 AM'));
var minutes = Math.floor((diff/1000)/60);
alert(minutes);
This solution will only work with en_US date format. But I'm using en_GB date format:21/09/2021 14:44:38. Any reason why?
You can check:
var diff = Math.abs(new Date('01/23/2020 06:30 PM') - new Date('01/23/2020 05:00 AM'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
var diff = Math.abs(new Date('21/09/2021 14:44:38') - new Date('21/09/2021 14:04:38'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
var diff = Math.abs(new Date('09/21/2021 14:44:38') - new Date('09/21/2021 14:04:38'));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
Thank you for your time.
My file:
https://docs.google.com/spreadsheets/d/1ExXtmQ8nyuV1o_UtabVJ-TifIbORItFMWjtN6ZlruWc/edit?usp=sharing
Date() doesn't support dd/mm/yyyy. This prevents ambiguity for cases like 1/2/2014 that yields into 2 possible dates, Jan 2 and Feb 1. So it only supports the mm/dd/yyyy as its standard format.
One way to converting it properly is to split the date.
function myFunction() {
startDate = '21/09/2021 14:44:38';
endDate = '21/09/2021 14:04:38';
var diff = Math.abs(convertGBDatetoDate(startDate) - convertGBDatetoDate(endDate));
console.log(diff);
var minutes = Math.floor((diff/1000)/60);
console.log(minutes);
}
function convertGBDatetoDate(string){
var [sD, sM, sY] = string.split(' ')[0].split('/').map(i=>Number(i));
var [sh, sm, ss] = string.split(' ')[1].split(':').map(i=>Number(i));
return new Date(sY,sM - 1,sD,sh,sm,ss);
}
Someone commented above, but then deleted, to use getTime().
Read here.
So I think this works. I don't even need to worry about date formats. I can just get the range with getRange() and getValue(). Then I can use this simple code:
var end, start;
start = new Date("Tue Sep 21 2021 20:00:00 GMT+0100 (British Summer Time)");
end = new Date("Tue Sep 21 2021 20:33:17 GMT+0100 (British Summer Time)");
console.log('Operation took ' + (((end.getTime() - start.getTime())/1000)/60) + ' min');
I'm looking for some help with my coursework as I've spent the last 8 hours trying to find a way to do what i'm trying to accomplish.
Now I have to use JavaScript, cannot use plugins but i can use the jQuery Library.
I'm basically trying to assign weeks to the semesters of the university year, so we say 29th September 2014 (Monday) to 26th January which is around 15 weeks.
Now I'm using something like this:
Date.prototype.getWeek = function() {
var firstJan = new Date(2014,0,1);
var today = new Date(2014, 9, 14);
var firstMonSem1 = new Date(2014, 8, 29);
var firstMonSem2 = new Date(this.getFullYear(), 1, 1);
var dayOfYear = ((today - firstJan + 86400000)/86400000);
var startWeekSem1 = ((firstMonSem1 - firstJan + 86400000)/86400000);
var startWeekSem2 = ((firstMonSem2 - firstJan + 86400000)/86400000);
var currentWeekNumber = Math.ceil(dayOfYear/7);
var startWeekNumberSem1 = Math.ceil(startWeekSem1/7);
var startWeekNumberSem2 = Math.ceil(startWeekSem2/7);
var output = {current: currentWeekNumber, sem1: startWeekNumberSem1, sem2: startWeekNumberSem2};
return output;
};
So i'm returning the current week of the year, semester start date for semester 1 and 2.
But for this example let's only focus on the first is 29th September (Monday) until 26th January which is around 15 weeks.
Now i've worked out based on the values i get when the semester starts and finishes including a 4 week holiday over the christmas period. And then I have an array for the index of which week of the semester we are in, in comparison to the week of the year (this way it could be week 41 in the year and based on the index array I would know that this is week 2).
Here's the code (note: it works!)
var today = new Date();
var info = today.getWeek();
if (info['current'] >= info['sem1'] && info['current'] <= (info['sem1'] + 18)) {
// Semester 1
var index = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var yearWeeks = [];
var count = 1;
for (var i = info['sem1']; i < (info['sem1'] + 18); i++) {
if (count !== 12 && count !== 13 && count !== 14) {
yearWeeks.push(i);
}
count++;
}
var rightIndex = $.inArray(info['current'], yearWeeks);
var x = 1;
while (x <= 15) {
if (x >= rightIndex) {
var weekOption = $("<option/>", {
"value" : x,
html : "Week "+x
}).appendTo(week);
}
x++;
}
}
So what I do here is append to a select all the weeks that are greater than the current week, so if we are in week 5 then there won't be a week 1,2,3,4 for the sake of this example (it's because in the project we are selecting a week to make a booking on but that's irrelevant).
Now, the problem.
This all works fantastically but there is a major catch, the week changes on Wednesday for example:
Week 1 is commencing 29th of September (Monday)
Week 2 starts 8th October (Wednesday)
Week 3 starts 15th October (Wednesday)
So every time the week changes on the Wednesday, now as the idea is that this system is being implemented so you can book room for that given week aka Monday - Friday, I need the weeks to update every Monday rather than Wednesday.
I really need help with this, and I know it might be a lot to grasp. However, I appreciate all the help I can get.
Thank you.
I think you need to replace this line:
var currentWeekNumber = Math.ceil(dayOfYear/7);
To be:
var currentWeekNumber = Math.ceil((dayOfYear + 5)/7);
To make a week start from Wednesday. In such case, the week of Day 2 (Tuesday) is Math.ceil((2+5)/7)=1, while Day 3 (Wednesday) is Math.ceil((3+5)/7)=2.
I worked it out some and hope it helps. This is not just for 2014 that you use, but for the current year. With some adaptation you can adjust.
You get the first of the year and get the offset of the day-number. Then you calculate the current day and subtract. The result will help you get the weeknr.
The week starts on Monday (where in other regions it may be on Sunday).
I created a fiddle, so you can play with it:
http://jsfiddle.net/djwave28/r0m4sokv/
This is an abstract from that fiddle:
// set an offset
var offset = 0;
var now = new Date();
var testday = new Date(now.getTime() + offset * 24 * 60 * 60 * 1000);
var firstofyear = new Date(testday.getFullYear(), 0, 1);
var firstdayoffset = firstofyear.getDay();
var daynr = Math.ceil((testday - firstofyear) / 86400000);
var weeknr = (daynr - firstdayoffset) / 7;
i am looking to display the date plus 1 month inside a div which will be used to display next invoice date. i have seen a few examples in various places, but could not implement. I also saw that there were many solutions, and some controversy surrounding each one.
Once you have a date object, just call setMonth(), passing in the current number of months plus 1.
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
You can either use this : http://jsfiddle.net/dfA8b/ if you need same date of the next month
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text(invoiceDt.toDateString());
Or
You can use this : http://jsfiddle.net/hjSDu/ if you need 30 days month(mostly used for invoice purposes)
var invoiceDt = new Date();
var days = 30;
invoiceDt.setDate(invoiceDt.getDate()+days);
$('#invoiceDate').text(invoiceDt.toDateString());
For the formatting purpose :
http://jsfiddle.net/7bU6n/
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text((invoiceDt.getMonth()+1) +"-"+ invoiceDt.getDate() +"-" + invoiceDt.getFullYear());
also see : https://stackoverflow.com/a/1643468/3603806
1 month is not so clear... what You mean? 31, 30 days or if exists simply same date of the following month?
1st case: (assuming 31 days)
var d = new Date(),
dplus31 = d.getDate() + 31;
d.setDate(dplus31);
console.debug(d, dplus31);
2nd case: one month
var d = new Date(),
dplus1 = d.getMonth() + 1;
d.setMonth(dplus1);
console.debug(d, dplus1);
..but even in this case there are some edge cases (ex. 31 January)
hope it helps
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.
I am sure that a lot of people asked this question but when I checked the answers it seems to me that they are wrong that what I found
var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'
var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be 1 july
I know that .getDate() return from 1-31 but Does the browser or the javascript increase only the day without updating the month and the year ?
and in this case Should I write an algorithm to handle this ? or there is another way ?
Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
JSFiddle
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
There is issue of 31st and 28th Feb with getDate() I use this function getTime and 24*60*60*1000 = 86400000
Use this function:
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
Example as below:
var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");
var amountToIncreaseWith = 1; //Edit this number to required input
console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
use this i think it is useful for you
var endDate=startDate.setDate(startDate.getDate() + 1);
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
add one day in javascript in one line
NB: if you want to add a specific number of days ... just replace 1 with the number of days you want
new Date(new Date().setDate(new Date().getDate() + 1))
console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
i know it's been long time since this is posted but here's my answer
function addDays(date, n)
{
const oneDayInMs = 86400 * 1000;
return new Date(Date.parse(date) + (n * oneDayInMs));
}
addDays(new Date(), 1);
Just for the sake of adding functions to the Date prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.
If you're using DateJS a line like this should do the trick:
Date.parse(startdate).add(1).days();
You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.
The below will add a single day to a current time. I believe this will handle daylight saving times, etc.
function increment_date (date) {
let old_date = new Date (date);
date.setDate (old_date.getDate() + 1);
while (date.getDate() == old_date.getDate()) {
date.setHours (date.getHours() + 1);
}
date.setHours (0);
}