Incrementing a Date in JavaScript

Incrementing a date in JavaScript

Three options for you:

1. Using just JavaScript's Date object (no libraries):

My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:

// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);

This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:

// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());

How can I add 1 day to current date?

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);

What's the simplest way to decrement a date in Javascript by 1 day?

var d = new Date();

d.setDate(d.getDate() - 1);

console.log(d);

How to increment date and how to disable previous dates in javascript?

Try this:

// Disable date

var input = document.getElementById("preDate");

var today = new Date();

var day = today.getDate()+1;

var mon = new String(today.getMonth()+1); //January is 0!

var yr = today.getFullYear();

if (mon.length > 0) {

mon = `0${mon}`;

}

if (day < 10) {

day = `0${day}`;

}

var date = `${yr}-${mon}-${day}`;

input.disabled = false;

input.setAttribute('min', date);

input.value = date;

console.log(date);
<div class="form-group col-3 rfdate">

<label class="col-sm-6 control-label p-sm-0">Refund Date</label>

<input type="date" class="form-control" id="preDate" name="preDate" />

</div>

Incrementing an ISO date string in JavaScript (e.g. '2014-03-30' - '2014-03-31')

This is caused by Daylight saving adjustment that happened on that date. March 30, 2014: Europe starts Daylight Saving Time

Fix it by using UTCDate instead:

var getNextDay = function(day) {
var date = new Date(day);
date.setUTCDate(date.getUTCDate() + 1);
return date.toISOString().slice(0, 10);
};

Stuck on incrementing date in JavaScript

While I haven't invested enough time trying to understand what you're really trying to do, it seems like there's a lot of unnecessary code. I'll leave it to you to decipher what you need.

I can only express that the below code is in an in-between state. It includes a number of changes, most of which I'll point out, but I didn't want to change it too drastically that it all looked foreign. So even the code below has much to be improved on.

Significant changes include:

  1. Because your URL is increasing by one, you may benefit by using a function generator. Inside it increases the date by calling setDate on itself using it's own date + 1. It also uses a string function, padStart, to ensure months and days are always two-digit.

  2. Getting rid of firstRun variable as it is no longer needed

  3. Inside your grabOpenPDF, all you need to do is get the next value returned by the URL generator function

let URL_GEN = UrlGenerator('blank'),

URL = URL_GEN.next().value;

//Starts the task.

//1

function start(load) {

let startDate = new Date(document.querySelector('#date-input').value)



// overwrite global with values

URL_GEN = UrlGenerator('blank', startDate)

URL = URL_GEN.next().value



console.log("Current Address: " + URL);

if (load === 1) {

console.log("Event load active.");

let maxDay = document.querySelector('#maxNumberDays').value;

grabOpenPDF(maxDay);

} else {

console.log("Event load skip.")

let maxDay = document.getElementById('maxNumberDays').value;

}

}

/* URL generator */

function* UrlGenerator(url, dt=new Date()) {

while (true){

yield url + dt.getFullYear() + (''+(dt.getMonth()+1)).padStart(2,'0') + (''+dt.getDate()).padStart(2,'0');



// increase day for next iteration

dt.setDate(dt.getDate()+1);

}

}

// will open x number of new windows containing URL

function grabOpenPDF(maxNumberDays) {

//Set the variable for max days.

for (let i=0; i < maxNumberDays; i++) {

console.log("It works: " + i, URL);

URL = URL_GEN.next().value;

}

}
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>

<input type="date" id="date-input" value="12/29/2018" required />

<input type="maxNumberDays" id="maxNumberDays" value="5" max="31" required />

<button id="startPDFApp" onClick="start()">Print PDFs</button>

<button id="startPDFApp" onClick="start(1)">Load PDFs</button>

<div id="info"></div>

javascript for loop incrementing momentjs date by 1 day,

date.add will mutate the initial date. If you want to mutate the initial date, you can just add 1 each time:

dates.push({ date: date.add(1, "days").format("YYYY-MM-DD") });

Your other option is to clone the date on each loop to make sure you're not mutating the original date:

const copiedDate = moment(date);
dates.push({ date: copiedDate.add(i, "days").format("YYYY-MM-DD") });

Increment Date by 1 set state

I believe it's because date.setDate() mutates the original date and React doesn't handle mutatable state (so it doesn't update/rerender the DOM). Instead, a workaround is to update a number in days which then updates the date...

function App() {
const [date, updateDate] = React.useState(new Date());
const [days, setDays] = React.useState(0);

const incrementDate = React.useCallback(() => {
setDays(prevState => prevState + 1);
}, []);

const decrementDate = React.useCallback(() => {
setDays(prevState => prevState - 1);
}, []);

React.useEffect(() => {
updateDate(prevState => new Date(Date.now() + days * 24 * 60 * 60 * 1000));
}, [days, updateDate])

return (
<div className="app">
<h1>Selected Date:</h1>
<p>{date.toString()}</p>
<button onClick={incrementDate}>Increment</button>
<button onClick={decrementDate}>Decrement</button>
</div>
);
}

// Render it
ReactDOM.render(
<App />,
document.getElementById("react")
);
.app {
font-family: sans-serif;
text-align: center;
}

.select {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>
<div id="react"></div>


Related Topics



Leave a reply



Submit