I bet this is something really silly but I am tired and looking for a quick escape so please indulge me. Objective is to be able to add arbitrary days to a date constructed from a string like 2015-01-01.
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = date.getMonth().toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month + '-' + day;
}
And then :
I get the output which is wrong because I am adding 90 days..
Two dates: 2015-01-01 2015-02-31
The problem lies in this line:
var month = date.getMonth().toString();
The function Date.getMonth() returns “the month (0-11) in the specified date according to local time”. January is 0, December is 11, so you need to add 1 to the output:
var month = "" + (date.getMonth()+1);
var month = date.getMonth().toString(); prints the no of months starting from no 0 so the month number is reduced by 1 for eg. the value of january from date.getMonth(); would be 0 and so on till 11.
here's the correct version for your code
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
console.log("before conversion");
console.log(t1_date);//before conversion
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
console.log("after conversion");
console.log(t1_date);//after conversion
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var month1=(month+1).toString();
month1 = month1.length > 1 ? month1 : '0' + month1;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month1 + '-' + day;
}
Never parse strings with the Date constructor, always manually parse them. An ISO date without a timezone should be treated as local*, however ES5 said to treat it as UTC, then ECMAScript 2015 inferred to treat them as local (hooray for consistency) but then the implementors decided to treat them as UTC again, so browsers might do either (or NaN).
So the sensible thing is to manually parse them as local.
Outputting as a local ISO date is also fairly simple.
* Where local means per system settings.
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
document.write(parseISODate('2015-01-01') + '<br>');
function toISODate(date) {
function z(n){return ('0'+n).slice(-2)}
return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate());
}
document.write(toISODate(parseISODate('2015-01-01')));
To add 90 days, it is simpler to just add 90 days to the date:
var d = new Date(2015,0,1); // 1 January 2015
d.setDate(d.getDate() + 90); // add 90 days
document.write(d.toLocaleString()); // 1 April 2015
I have written these two javascript functions:
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
and
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
The first one should return a new date with the same year/month/day but with a different hour of the day (e.g. switch 2015-04-05 15:00 to 2015-04-05 16:00).
The second one should just return a date-string in the format dd.MM.yyyy.
Now if I call
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
Where hour is a function parameter and for example 15 (tested with alert), in my "dateLabel" it says 05.01.2015. But if I do
alert (selectedDate);
the result is: Sun Apr 05 2015 15:52:26 GMT+0200 (CEST) => now.
selectedDate is not modified between the calls (alert and set the innerHTML).
I think the two functions do not do what I suppose them to, but maybe you find the mistake.
Thank you !
EDIT:
I tried this code:
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
document.getElementById("datumLabel").innerHTML = getDateDescriptionFromDate(startDate); // 05.01.2015
I don't know why you're surprised by what selectedDate is returning. You have only set it to new Date() (now). Nothing in the code is manipulating this variable from the point of creation.
You are, however, manipulating the value and storing the change in startDate and dateLabel.innerHTML. You would only notice the formatting though since the second function strips any change in "time" (done by the first function).
So, in short: You create a date (now), change the time, then format it to only show date.
var selectedDate = new Date();
//selectedDate value = the date and time right now
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
//startDate value = whatever selectedDate was + hours sent as parameter
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
//Formatted value of startDate, to only show date
As per comment:
You're missing that month in javascript is zero-based. So you'll have to do something like:
var month = date.getMonth() + 1; //in the second function
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, 15);
document.getElementById("dateLabel").innerHTML = 'Your current system date: ' + getDateDescriptionFromDate(startDate);
<div id="dateLabel"></div>
If you try this, this should give you save value for your alert and Label, the value you are using for the Label is different than the value you are trying to use alert on.
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
var startDateDesc = getDateDescriptionFromDate(startDate);
alert(startDateDesc) // 05.01.2015
document.getElementById("datumLabel").innerHTML = startDateDesc; // 05.01.2015
how is it possble to get the date in this format ? 28/09/2013
what i am getting now is,
Fri Sep 27 2013 15:19:01 GMT+0530 (Sri Lanka Standard Time)
This is the code i have written to get that..
var date = new Date();
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000);
alert(tomorrow);
and i need to see weather, is the given date is tomorrow. something like this when i give 28/09/2013 it should alert as tomorrow or not.
any help is highlight appreciated.
NOTE : i only need to compare with date. 28/09/2013 === tomorrow
You can try following to get the next day :
var myDate=new Date();
myDate.setDate(myDate.getDate()+1);
// format a date
var dt = myDate.getDate() + '/' + ("0" + (myDate.getMonth() + 1)).slice(-2) + '/' + myDate.getFullYear();
console.log(dt);
Here is the demo : http://jsfiddle.net/5Yj3V/3/
Moment.js will do that for you very easily.
moment().add('days', 1).format('L');
I would use the DateJS library.
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy");
Try the below fiddle using javascript.
var tomorrow = new Date();
var newdate = new Date();
var month = (newdate.getMonth()+1);
newdate.setDate(tomorrow.getDate() + 1);
if (month < 10)
{
month = '0' + (newdate.getMonth()+1);
}
alert(newdate);
alert(newdate.getDate() + '/' + month + '/' + newdate.getFullYear());
I have a json date like \/Date(1334514600000)\/ in my response and when I convert it in javascript then I got this date Tue Apr 17 2012 11:37:10 GMT+0530 (India Standard Time),
but I need the date format like 17/04/2012 and I fail every time. Can anyone tell me how can I resolve it?
I don't think that the other posted answers are quite right, you have already accepted one as working for you so I won't edit it.
Here is an updated version of your accepted answer.
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
alert(date);
It uses a technique from this answer to extract the epoch from the JSON date.
I found very helpful the row1 answer, however i got stuck on the format for input type="date" as only returns one string for decimals under 10, I was able to modify to work on input type="date", I basically adapted the code from row1 to the code from the link http://venkatbaggu.com/convert-json-date-to-date-format-in-jquery/
I was able through jquery .val add the date to the input
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString));
var month = ("0" + (currentTime.getMonth() + 1)).slice(-2);
var day = ("0" + currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = year + '-' + month + '-' + day;
alert(date);
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);
It's answer to your question...
Build the date object with your timestamp
var currentTime = new Date(1334514600000)
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);
it works
http://jsfiddle.net/ChgUa/
//parse JSON formatted date to javascript date object
var bdate = new Date(parseInt(emp.Birthdate.substr(6)));
//format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", bdate);
Easiest way of formatting date is by using pipes if you are using Angular.
Click here
//in .ts file
ngOnInit() {
this.currentDate = new Date()
}
//in html file
<p>Current date is:</p>{{currentDate | date: 'dd/MM/yyyy'}}
//Output: 22/04/2020
Here is an updated version of your accepted answer. DD/MM/YYYY Format Get Try This..
var dateString = "/Date(1623781800000+0530)/"+.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if (month.toString().length == 1)
month = "0" + month.toString();
if (day.toString().length == 1){
day = "0" + currentTime.getDate();}
var datenew = day + "/" + month + "/" + year;
var Date = new Date(Tue Jun 15 2021 23:52:47 GMT+0800 (Malaysia Time)).toDateString(); console.log(Date);
Result == Tue Jun 15 2021
I need to increment a date value by one day in JavaScript.
For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.
How can I increment a date by a day?
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());
2. Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
3. Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
Tomorrow in one line in pure JS but it's ugly !
new Date(new Date().setDate(new Date().getDate() + 1))
Here is the result :
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.
const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS
.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Two methods:
1:
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)
2: Similar to the previous method
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Via native JS, to add one day you may do following:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
Another option is to use moment library:
const date = moment().add(14, "days").toDate()
Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
Slice the date from the returned value and then increment by the number of days you want.
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):
Date.prototype.shiftDays = function(days){
days = parseInt(days, 10);
this.setDate(this.getDate() + days);
return this;
}
$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
Result:
Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200
Adding one Hour to the date, will make it work perfectly (but does not solve the problem).
$date = new Date(2014, 9, 16,0,1,1);
Result:
Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
Incrementing date's year with vanilla js:
start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020
Just in case someone wants to increment other value than the date (day)
Timezone/daylight savings aware date increment for JavaScript dates:
function nextDay(date) {
const sign = v => (v < 0 ? -1 : +1);
const result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
const offset = result.getTimezoneOffset();
return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
This a simpler method ,
and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
Use this function, it´s solved my problem:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}
Assigning the Increment of current date to other Variable
let startDate=new Date();
let endDate=new Date();
endDate.setDate(startDate.getDate() + 1)
console.log(startDate,endDate)