How to get 30 days prior to current date? - javascript

I have a start calendar input box and an end calendar input box. We want defaults start calendar input box 30 days prior to current date and the end calendar input box to be the current date. Here is my date vars.
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth(),
yyyy = today.getFullYear(),
month = ["January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October" "November", "December"],
startdate = month[mm] + ", " + yyyy.toString();
The end date would be something like var enddate = startdate - 30; Obviously this won't work.
So if the current date is December 30, 2011 I'd want the start date to read December 1, 2011.
EDIT: My question was answered... sort of. Date.today(); and Date.today().add(-30); work but I need the date in the format of January 13, 2012. Not Fri Jan 13 2012 10:48:56 GMT -055 (EST). Any help?
MORE EDIT: As of this writing it's 2018. Just use Moment.js. It's the best.

To subtract days from a JS Date object you can use the setDate() method, along with the date to start the calculation from. This will return an epoch timestamp as an integer, so to convert this to a Date you'll need to again provide it to the Date() object constructor. The final example would look like this:
var today = new Date();
var priorDate = new Date(new Date().setDate(today.getDate() - 30));
console.log(today)
console.log(priorDate);

Try using the excellent Datejs JavaScript date library (the original is no longer maintained so you may be interested in this actively maintained fork instead):
Date.today().add(-30).days(); // or...
Date.today().add({days:-30});
[Edit]
See also the excellent Moment.js JavaScript date library:
moment().subtract(30, 'days'); // or...
moment().add(-30, 'days');

Here's an ugly solution for you:
var date = new Date(new Date().setDate(new Date().getDate() - 30));

startDate = new Date(today.getTime() - 30*24*60*60*1000);
The .getTime() method returns a standard JS timestamp (milliseconds since Jan 1/1970) on which you can use regular math operations, which can be fed back to the Date object directly.

Get next 30th day from today
let now = new Date()
console.log('Today: ' + now.toUTCString())
let next30days = new Date(now.setDate(now.getDate() + 30))
console.log('Next 30th day: ' + next30days.toUTCString())
Get last 30th day form today
let now = new Date()
console.log('Today: ' + now.toUTCString())
let last30days = new Date(now.setDate(now.getDate() - 30))
console.log('Last 30th day: ' + last30days.toUTCString())

Javascript can handle it without any external libraries.
var today = new Date();
var dateLimit = new Date(new Date().setDate(today.getDate() - 30));
document.write(today + "<br/>" + dateLimit)

Simple 1 liner Vanilla Javascript code :
const priorByDays = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
For example:
days = 7
Assume current date = Fri Sep 18 2020 01:33:26 GMT+0530
The result would be : Fri Sep 11 2020 01:34:03 GMT+0530
The beauty of this is you can manipulate it to get result in desired type
timestamp : Date.now() - days * 24 * 60 * 60 * 1000
ISOString: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()

Easy.(Using Vanilla JS)
let days=30;
this.maxDateTime = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
ISOFormat ?
let days=30;
this.maxDateTime = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();

let today = new Date()
let last30Days = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)
last30Days will be in Date Object

I will prefer moment js
startDate = moment().subtract(30, 'days').format('LL') // January 29, 2015
endDate = moment().format('LL'); // February 28, 2015

I use date.js. It handles this easily and takes care of all the leap-year nastiness.

This is an ES6 version
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getMonth()+1 + '/' + newDate.getDate() + '/' + newDate.getFullYear() )

You can do that simply through 1 line of code using moment in Node JS. :)
let lastOneMonthDate = moment().subtract(30,"days").utc().toISOString()
Don't want UTC format, EASIER :P
let lastOneMonthDate = moment().subtract(30,"days").toISOString()

If you aren't inclined to momentjs, you can use this:
let x = new Date()
x.toISOString(x.setDate(x.getDate())).slice(0, 10)
Basically it gets the current date (numeric value of date of current month) and then sets the value. Then it converts into ISO format from which I slice down the pure numeric date (i.e. 2019-09-23)
Hope it helps someone.

Use moment.js
let startDate = moment().subtract(30, "days").format('YYYY-MM-DD'); //2021-05-18
let endDate = moment().format('YYYY-MM-DD'); //2021-06-17

For anyone looking for the format 'dd month yyyy', here's what worked for me:
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getDate()+ ' ' +newDate.toLocaleString('default', {month: 'long'}) + ' ' + newDate.getFullYear() )

Related

why not get correctly date, (plus 1 day) in javascript? [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Incrementing a date in JavaScript
(19 answers)
How can I add 1 day to current date?
(10 answers)
Closed 12 months ago.
I am trying to get JavaScript to display tomorrows date in format (dd-mm-yyyy)
I have got this script which displays todays date in format (dd-mm-yyyy)
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
Displays: 25/2/2012 (todays date of this post)
But how do I get it to display tomorrows date in the same format i.e. 26/2/2012
I tried this:
var day = currentDate.getDate() + 1
However I could keep +1 and go over 31 obviously there are not >32 days in a month
Been searching for hours but seems to be no answer or solution around this?
This should fix it up real nice for you.
If you pass the Date constructor a time it will do the rest of the work.
24 hours 60 minutes 60 seconds 1000 milliseconds
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
One thing to keep in mind is that this method will return the date exactly 24 hours from now, which can be inaccurate around daylight savings time.
Phil's answer work's anytime:
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);
The reason I edited my post is because I myself created a bug which came to light during DST using my old method.
The JavaScript Date class handles this for you
var d = new Date(2012, 1, 29) // month is 0-based in the Date constructor
console.log(d.toLocaleDateString())
// Wed Feb 29 2012
d.setDate(d.getDate() + 1)
console.log(d.toLocaleDateString())
// Thu Mar 01 2012
console.log(d.getDate())
// 1
Method Date.prototype.setDate() accepts even arguments outside the standard range and changes the date accordingly.
function getTomorrow() {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1); // even 32 is acceptable
return `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`;
}
Using JS only(Pure js)
Today
new Date()
//Tue Oct 06 2020 12:34:29 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0, 0))
//Tue Oct 06 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0,0)).toLocaleDateString('fr-CA')
//"2020-10-06"
Tomorrow
new Date(+new Date() + 86400000);
//Wed Oct 07 2020 12:44:02 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0, 0) + 86400000);
//Wed Oct 07 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0,0)+ 86400000).toLocaleDateString('fr-CA')
//"2020-10-07"
//don't forget the '+' before new Date()
Day after tomorrow
Just multiply by two ex:- 2*86400000
You can find all the locale shortcodes from https://stackoverflow.com/a/3191729/7877099
I would use the DateJS library. It can do exactly that.
http://www.datejs.com/
The do the following:
var d = new Date.today().addDays(1).toString("dd-mm-yyyy");
Date.today() - gives you today at midnight.
The below uses a combination of Roderick and Phil's answers with two extra conditionals that account for single digit months/days.
Many APIs I've worked with are picky about this, and require dates to have eight digits (eg '02022017'), instead of the 6 or 7 digits the date class is going to give you in some situations.
function nextDayDate() {
// get today's date then add one
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
var month = nextDay.getMonth() + 1;
var day = nextDay.getDate();
var year = nextDay.getFullYear();
if (month < 10) { month = "0" + month }
if (day < 10) { day = "0" + day }
return month + day + year;
}
Use cases :
Date.tomorrow() // 1 day next
Date.daysNext(1) // alternative Date.tomorrow()
Date.daysNext(2) // 2 days next.
IF "tomorrow " is not depend of today but of another Date different of Date.now(), Don't use static methods but rather you must use non-static :
i.e: Fri Dec 05 2008
var dec5_2008=new Date(Date.parse('2008/12/05'));
dec5_2008.tomorrow(); // 2008/12/06
dec5_2008.tomorrow().day // 6
dec5_2008.tomorrow().month // 12
dec5_2008.tomorrow().year //2008
dec5_2008.daysNext(1); // the same as previous
dec5_2008.daysNext(7) // next week :)
API :
Dateold=Date;function Date(e){var t=null;if(e){t=new Dateold(e)}else{t=new Dateold}t.day=t.getDate();t.month=t.getMonth()+1;t.year=t.getFullYear();return t}Date.prototype.daysNext=function(e){if(!e){e=0}return new Date(this.getTime()+24*60*60*1e3*e)};Date.prototype.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)};Date.prototype.tomorrow=function(){return this.daysNext(1)};Date.prototype.yesterday=function(){return this.daysAgo(1)};Date.tomorrow=function(){return Date.daysNext(1)};Date.yesterday=function(){return Date.daysAgo(1)};Date.daysNext=function(e){if(!e){e=0}return new Date((new Date).getTime()+24*60*60*1e3*e)};Date.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)}
Method 1: If you don't have problem in using other library, then this could work for you using moment.js
moment().add('days', 1).format('L');
Method 2: Using Date.js,
<script type="text/javascript" src="date.js"></script>
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy");
This method uses external library and not the native Date library.
As my bootstrap-datetimepicker was using moment.js and native date library, I preferred method 1. This question mentions these and some other methods.
Its really simple:
1: Create date object with today' date and time.
2: Use date object methods to retrieve day, month and full year and concatenate them using the + operator.
Sample Code:
var my_date = new Date();
var tomorrow_date = (my_date.getDate() + 1) + "-" + (my_date.getMonth() + 1) + "-" + my_date.getFullYear();
document.write(tomorrow_date);
function getMonday(d)
{
// var day = d.getDay();
var day = #Config.WeekStartOn
diff = d.getDate() - day + (day == 0 ? -6 : 0);
return new Date(d.setDate(diff));
}
The same as the original answer, but in one line:
var tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
The numbers stand for 24 hours 60 minutes 60 seconds 1000 milliseconds.
you can try this:
function Tomorrow(date=false) {
var givendate = (date!=false) ? new Date(date) : new Date();
givendate.setDate(givendate.getDate() + 1);
var day = givendate.getUTCDate()
var month = givendate.getUTCMonth()+1
var year = givendate.getUTCFullYear()
result ="<b>" + day + "/" + month + "/" + year + "</b>";
return result;
}
var day = Tomorrow('2020-06-30');
console.log('tomorrows1: '+Tomorrow('2020-06-30'));
console.log('tomorrows2: '+Tomorrow());
//to get date of tomorrow
let tomorrow=new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()+1}-${(new Date()).getDate()+1}`);
//for dd-mm-yy format
tomorrow=`${tomorrow.getDate()}-${tomorrow.getMonth()+1}-${((tomorrow.getFullYear()).toString()).slice(-2)}`;
document.write(tomorrow)
//-----------Date Configuration march 18,2014----------------------
//alert(DateFilter);
var date = new Date();
y = date.getFullYear(), m = date.getMonth();
var EndDate = new Date();
switch (DateFilter) {
case 'today': var StartDate = EndDate; //todays date
break;
case 'yesterday':
var d = new Date();
var previousDate = new Date(d.getTime() - 1000 * 60 * 60 * 24);
var StartDate = new Date(previousDate.yyyymmdd()); //yesterday Date
break;
case 'tomorrow':
var d = new Date();
var NextDate = new Date(d.getTime() + 1000 * 60 * 60 * 24);
var StartDate = new Date(NextDate.yyyymmdd()); //tomorrow Date
break;
case 'thisweek': var StartDate = getMonday(new Date()); //1st date of this week
break;
case 'thismonth': var StartDate = new Date(y, m, 1); //1st date of this month
break;
case 'thisyear': var StartDate = new Date("01/01/" + date.getFullYear()); //1st date of this year
break;
case 'custom': //var StartDate = $("#txtFromDate").val();
break;
default:
var d = new Date();
var StartDate = new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000); //one month ago date from now.
}
if (DateFilter != "custom") {
var SDate = $.datepicker.formatDate('#Config.DateFormat', StartDate); $("#txtFromDate").val(SDate);
var EDate = $.datepicker.formatDate('#Config.DateFormat', EndDate); $("#txtToDate").val(EDate);
}
//-----------Date Configuration march 18,2014----------------------
var curDate = new Date().toLocaleString().split(',')[0];
Simply! in dd.mm.yyyy format.
Date.prototype.NextDay = function (e) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + ("string" == typeof e ? parseInt(e, 10) : e));
}
// tomorrow
console.log(new Date().NextDay(1))
// day after tomorrow
console.log(new Date().NextDay(2))

Increment date by one day to a set epoch date

I would like to increment a (epoch) date by one day.
So far I have:
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
This spits out 25 so I am on the right track. How would I convert it back to a Date object?
This is going to be in this map function:
return data.map(t => ({
id: t.id,
start_date: new Date(parseInt(t.date_created, 10)),
duration: // here, taking the above start date and adding one day
)
}));
I think you can add day in milliseconds to achieve this.
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
let nextDay = +date + (24 * 60 * 60 * 1000) // 1 day in millisecond
nextDay = new Date(nextDay)
console.log(nextDay)
You can also use momentjs in following way:
var date = 1535162451650
date = moment(abc)
console.log('date', date.format('DD MM YYYY'))
date = date.add(1, 'day')
console.log('date', date.format('DD MM YYYY'))
How about this?
var options = {
id: t.id,
start_date: new Date(parseInt(t.date_created, 10))
};
options.duration = new Date(options.start_date.getTime());
options.duration.setDate(options.duration.getDate() + 1);
return data.map(t => (options));
I think I figured it out. Looks ugly but seems to work
let date = "1535162451650";
console.log(new Date (new Date(parseInt(date, 10)).setDate(new Date(parseInt(date, 10)).getDate() + 1)));
// gives me aug 25 2018
Is there a cleaner way to do this? haha

Today's date -30 days in JavaScript

I need to get today's date -30 days but in the format of: "2016-06-08"
I have tried setDate(date.getDate() - 30); for -30 days.
I have tried date.toISOString().split('T')[0] for the format.
Both work, but somehow cannot be used together.
setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"
You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:
var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>
If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.
Please note that you would be better to use something like moment.js for this rather than reinventing the wheel. However a straight JS solution without libraries is something like:
var date = new Date();
date.setDate(date.getDate() - 30);
sets date to 30 days ago. (JS automatically accounts for leap years and rolling over months less than 30 days, and into the previous year)
now just output it like you want (gives you more control over the output). Note we are prepending a '0' so that numbers less than 10 are 0 prefixed
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)
// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);
const currentDate = new Date();
// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;
const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);
console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));
Today's date -30 days in this format: "YYYY-MM-DD":
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2021-02-05"
Today's date -30 days but get all days in this format: "YYYY-MM-DD":
var daysDate = [];
for(var i = 1; i<= 30; i++) {
var date = new Date();
date.setDate(date.getDate() - i);
daysDate.push(date.toISOString().split('T')[0]); // ["2021-02-05", "2021-02-04", ...]
}
Simply you can calculate in terms of timestamp
var date = new Date(); // Current date
console.log(date.toDateString())
var pre_date = new Date(date.getTime() - 30*24*60*60*1000);
// You will get the Date object 30 days earlier to current date.
console.log(pre_date.toDateString())
Here 30*24*60*60*1000 refers to time difference in miliseconds.

How can I add 1 day to current date?

I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

JavaScript how to get tomorrows date in format dd-mm-yy [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Incrementing a date in JavaScript
(19 answers)
How can I add 1 day to current date?
(10 answers)
Closed 12 months ago.
I am trying to get JavaScript to display tomorrows date in format (dd-mm-yyyy)
I have got this script which displays todays date in format (dd-mm-yyyy)
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
Displays: 25/2/2012 (todays date of this post)
But how do I get it to display tomorrows date in the same format i.e. 26/2/2012
I tried this:
var day = currentDate.getDate() + 1
However I could keep +1 and go over 31 obviously there are not >32 days in a month
Been searching for hours but seems to be no answer or solution around this?
This should fix it up real nice for you.
If you pass the Date constructor a time it will do the rest of the work.
24 hours 60 minutes 60 seconds 1000 milliseconds
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
One thing to keep in mind is that this method will return the date exactly 24 hours from now, which can be inaccurate around daylight savings time.
Phil's answer work's anytime:
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);
The reason I edited my post is because I myself created a bug which came to light during DST using my old method.
The JavaScript Date class handles this for you
var d = new Date(2012, 1, 29) // month is 0-based in the Date constructor
console.log(d.toLocaleDateString())
// Wed Feb 29 2012
d.setDate(d.getDate() + 1)
console.log(d.toLocaleDateString())
// Thu Mar 01 2012
console.log(d.getDate())
// 1
Method Date.prototype.setDate() accepts even arguments outside the standard range and changes the date accordingly.
function getTomorrow() {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1); // even 32 is acceptable
return `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`;
}
Using JS only(Pure js)
Today
new Date()
//Tue Oct 06 2020 12:34:29 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0, 0))
//Tue Oct 06 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0,0)).toLocaleDateString('fr-CA')
//"2020-10-06"
Tomorrow
new Date(+new Date() + 86400000);
//Wed Oct 07 2020 12:44:02 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0, 0) + 86400000);
//Wed Oct 07 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0,0)+ 86400000).toLocaleDateString('fr-CA')
//"2020-10-07"
//don't forget the '+' before new Date()
Day after tomorrow
Just multiply by two ex:- 2*86400000
You can find all the locale shortcodes from https://stackoverflow.com/a/3191729/7877099
I would use the DateJS library. It can do exactly that.
http://www.datejs.com/
The do the following:
var d = new Date.today().addDays(1).toString("dd-mm-yyyy");
Date.today() - gives you today at midnight.
The below uses a combination of Roderick and Phil's answers with two extra conditionals that account for single digit months/days.
Many APIs I've worked with are picky about this, and require dates to have eight digits (eg '02022017'), instead of the 6 or 7 digits the date class is going to give you in some situations.
function nextDayDate() {
// get today's date then add one
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
var month = nextDay.getMonth() + 1;
var day = nextDay.getDate();
var year = nextDay.getFullYear();
if (month < 10) { month = "0" + month }
if (day < 10) { day = "0" + day }
return month + day + year;
}
Use cases :
Date.tomorrow() // 1 day next
Date.daysNext(1) // alternative Date.tomorrow()
Date.daysNext(2) // 2 days next.
IF "tomorrow " is not depend of today but of another Date different of Date.now(), Don't use static methods but rather you must use non-static :
i.e: Fri Dec 05 2008
var dec5_2008=new Date(Date.parse('2008/12/05'));
dec5_2008.tomorrow(); // 2008/12/06
dec5_2008.tomorrow().day // 6
dec5_2008.tomorrow().month // 12
dec5_2008.tomorrow().year //2008
dec5_2008.daysNext(1); // the same as previous
dec5_2008.daysNext(7) // next week :)
API :
Dateold=Date;function Date(e){var t=null;if(e){t=new Dateold(e)}else{t=new Dateold}t.day=t.getDate();t.month=t.getMonth()+1;t.year=t.getFullYear();return t}Date.prototype.daysNext=function(e){if(!e){e=0}return new Date(this.getTime()+24*60*60*1e3*e)};Date.prototype.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)};Date.prototype.tomorrow=function(){return this.daysNext(1)};Date.prototype.yesterday=function(){return this.daysAgo(1)};Date.tomorrow=function(){return Date.daysNext(1)};Date.yesterday=function(){return Date.daysAgo(1)};Date.daysNext=function(e){if(!e){e=0}return new Date((new Date).getTime()+24*60*60*1e3*e)};Date.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)}
Method 1: If you don't have problem in using other library, then this could work for you using moment.js
moment().add('days', 1).format('L');
Method 2: Using Date.js,
<script type="text/javascript" src="date.js"></script>
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy");
This method uses external library and not the native Date library.
As my bootstrap-datetimepicker was using moment.js and native date library, I preferred method 1. This question mentions these and some other methods.
Its really simple:
1: Create date object with today' date and time.
2: Use date object methods to retrieve day, month and full year and concatenate them using the + operator.
Sample Code:
var my_date = new Date();
var tomorrow_date = (my_date.getDate() + 1) + "-" + (my_date.getMonth() + 1) + "-" + my_date.getFullYear();
document.write(tomorrow_date);
function getMonday(d)
{
// var day = d.getDay();
var day = #Config.WeekStartOn
diff = d.getDate() - day + (day == 0 ? -6 : 0);
return new Date(d.setDate(diff));
}
The same as the original answer, but in one line:
var tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
The numbers stand for 24 hours 60 minutes 60 seconds 1000 milliseconds.
you can try this:
function Tomorrow(date=false) {
var givendate = (date!=false) ? new Date(date) : new Date();
givendate.setDate(givendate.getDate() + 1);
var day = givendate.getUTCDate()
var month = givendate.getUTCMonth()+1
var year = givendate.getUTCFullYear()
result ="<b>" + day + "/" + month + "/" + year + "</b>";
return result;
}
var day = Tomorrow('2020-06-30');
console.log('tomorrows1: '+Tomorrow('2020-06-30'));
console.log('tomorrows2: '+Tomorrow());
//to get date of tomorrow
let tomorrow=new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()+1}-${(new Date()).getDate()+1}`);
//for dd-mm-yy format
tomorrow=`${tomorrow.getDate()}-${tomorrow.getMonth()+1}-${((tomorrow.getFullYear()).toString()).slice(-2)}`;
document.write(tomorrow)
//-----------Date Configuration march 18,2014----------------------
//alert(DateFilter);
var date = new Date();
y = date.getFullYear(), m = date.getMonth();
var EndDate = new Date();
switch (DateFilter) {
case 'today': var StartDate = EndDate; //todays date
break;
case 'yesterday':
var d = new Date();
var previousDate = new Date(d.getTime() - 1000 * 60 * 60 * 24);
var StartDate = new Date(previousDate.yyyymmdd()); //yesterday Date
break;
case 'tomorrow':
var d = new Date();
var NextDate = new Date(d.getTime() + 1000 * 60 * 60 * 24);
var StartDate = new Date(NextDate.yyyymmdd()); //tomorrow Date
break;
case 'thisweek': var StartDate = getMonday(new Date()); //1st date of this week
break;
case 'thismonth': var StartDate = new Date(y, m, 1); //1st date of this month
break;
case 'thisyear': var StartDate = new Date("01/01/" + date.getFullYear()); //1st date of this year
break;
case 'custom': //var StartDate = $("#txtFromDate").val();
break;
default:
var d = new Date();
var StartDate = new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000); //one month ago date from now.
}
if (DateFilter != "custom") {
var SDate = $.datepicker.formatDate('#Config.DateFormat', StartDate); $("#txtFromDate").val(SDate);
var EDate = $.datepicker.formatDate('#Config.DateFormat', EndDate); $("#txtToDate").val(EDate);
}
//-----------Date Configuration march 18,2014----------------------
var curDate = new Date().toLocaleString().split(',')[0];
Simply! in dd.mm.yyyy format.
Date.prototype.NextDay = function (e) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + ("string" == typeof e ? parseInt(e, 10) : e));
}
// tomorrow
console.log(new Date().NextDay(1))
// day after tomorrow
console.log(new Date().NextDay(2))

Categories

Resources