date format javascript - javascript

The script below returns dates in this format:
Fri Apr 21 2011 12:18:25 GMT+0200
Fri Apr 22 2011 12:18:25 GMT+0200
Fri Apr 29 2011 12:18:25 GMT+0200
My question is: how to get dates in this format:
dd/mm/year like so: 21/04/2001
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 8);
{
jQuery("input[id*='now']").val(now);
jQuery("input[id*='tomorrow']").val(tomorrow);
jQuery("input[id*='nextweek']").val(nextWeek);
}

var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
alert(day + "/" + month + "/" + year);
Try this.

I suggest you can use Steve Levithan's dateformat script: http://blog.stevenlevithan.com/archives/date-time-format

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
You just may wrap it or use one of the existing helpers

Check out moment.js! It's a really powerful little library for working with Dates in JavaScript.
var today = moment(new Date());
today.format("D/M/YYYY"); // "4/11/2012"
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:42 PM"
// in one line...
moment().format("D/M/YYYY"); // "4/11/2012"
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:42 PM"
Another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.

The formatting library https://github.com/anywhichway/stringformatter will address this issue and more. It supports most of the momentjs formats plus U, G, I, L, T, to return UTC, GTM, ISO, Local, and Time strings respectively. It also provides a consistent approach that can be used for formatting other things.
Format expressions using this library take the form of embedded Javascript objects, e.g.
format("{Date: {format: 'DD-MMM-YYYY hh:mm:ss:SSS A'}}",new Date('2015-04-12 00:12:23'));
will return
"12-Apr-2015 12:12:23:000 AM"

Using plain old JavaScript, something like this should work:
var formatDateString = function(s) {
var pad = function(x) { return ((x.length<2) ? "0" : "") + x; }
, dt = new Date("" + s), d, m, y;
if (dt.getTime()) {
d = pad(dt.getDate());
m = pad(dt.getMonth()+1);
y = dt.getFullYear();
return [d, m, y].join('/');
}
return null;
};
formatDateString("Fri Apr 21 2011 12:18:25 GMT+0200"); // => "21/04/2011"

If you're already using jquery UI and the date picker
var stringDate = $.datepicker.formatDate( 'dd/mm/yy', new Date() );

In pure Javascript:
function dmy(d) {
function pad2(n) {
return (n < 10) ? '0' + n : n;
}
return pad2(d.getUTCDate()) + '/' +
pad2(d.getUTCMonth() + 1) + '/' +
d.getUTCFullYear();
}

Related

Formatting JavaScript date

I have a string representing a date in the following format :
Jun 29, 2019 12:00:00 AM
I would like to format this date such as follows:
2019-06-29
Is there any way of doing this without using any external libraries?
I tried the following and it works fine in Chrome but not in Edge:
var stringDate = 'Jun 29, 2019 12:00:00 AM';
var date = new Date(stringDate).toISOString().slice(0,10);
Using an external lib like https://momentjs.com/ is of course the easiest option.
But if the dates are always in the format you say, maybe a little bit of regex and javascript might be all you need.
eg.
var resplitdate = /^(\w{3}) (\w{1,2}), (\w{4})/;
var months = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(",");
function pz(s, size) {
var r = s.toString();
while (r.length < size) r = '0' + r;
return r;
}
function convertDate(d) {
var splits = resplitdate.exec(d);
return splits[3] + '-' +
pz(months.indexOf(splits[1]) + 1, 2) + "-" +
pz(splits[2], 2);
}
var stringDate = 'Jun 29, 2019 12:00:00 AM';
console.log(stringDate, " = ", convertDate(stringDate));
You can use getFullYear(), getDay() and getDate() to get the values. You can then use padStart() to pad the beginning of each item with zeros.
var date = new Date('Jun 29, 2019 12:00:00 AM');
console.log(`${date.getFullYear()}-${String(date.getDay()).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`)
A simple way to format the date using javascript(only) could be as follows -
var stringDate = 'Jun 29, 2019 12:00:00 AM';
function appendLeadingZeroes(n){
if(n <= 9){
return "0" + n;
}
return n
}
let current_datetime = new Date(stringDate);
let formatted_date = current_datetime.getFullYear() + "-" + appendLeadingZeroes(current_datetime.getMonth() + 1) + "-" + appendLeadingZeroes(current_datetime.getDate())
console.log(formatted_date)

How to convert date format into different formate

Hello I want to convert
March 2018 to 032018
in jQuery.I used
var d = new Date($('.selected_month').find("td:first").text());
But it is giving result is:
Thu Mar 01 2018 00:00:00 GMT+0530 (IST)
You need to use getMonth() and getFullYear() on returned date object to format date as per requirement. Also, you need to add 1 to returned month as getMonth method is 0 index based:
(d.getMonth()+1).toString() + d.getFullYear().toString()
Try this
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
return [month,year].join('');
}
Call this function : formatDate('March 2018') // output : 032018
Try converting the date object you end up with to a string:
Try the following snippet, just change var d = new Date() to var d = new Date($('.selected_month').find("td:first").text()).
var d = new Date();
var twoDigitMonth = (d.getUTCMonth() + 1).toString().padStart(2, "0");
var year = d.getUTCFullYear();
var result = twoDigitMonth + year;
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...or try this...
console.log(
new Date("March 2018")
.toLocaleDateString('en-EN', {month: '2-digit',year: 'numeric'})
.replace('/','')
)

Get date in Italian Format as "Lunedì GG/MM" how to?

i've tried to do this :
var curr = new Date;
var first = curr.getDate() - curr.getDay();
var last = first + 7;
var firstday = new Date(curr.setDate(first + 1)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
But i get firstday = "Mon, 18 Jan 2016 09:14:44 GMT" and
lastday = "Sun, 24 Jan 2016 09:14:44 GMT". How can i use italian name of the day and format DD/MM as "Lunedì 10/01" (Monday 10 of January in english).
Thanks
Cris
Without having to use external libraries, you want to use the toLocaleString() function.
var options = {'weekday': 'long', 'month': '2-digit', 'day': '2-digit'};
var date = new Date().toLocaleString('it-IT', options);
document.write(date)
Reference with all the possible options
Use moment.js for that
moment.locale('it');
document.write(moment().format('dddd DD/MM'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/locale/it.js"></script>
hi you can do it by using moment.js ,By default, Moment.js comes with English locale strings. If you need other locales, you can load them into Moment.js like this:
moment.locale('it');
var currentDate = moment();
//fist
alert(moment().format('dddd, MMMM Do YYYY, h:mm:ss'));
//last
alert(currentDate.add(7, 'days').format('dddd, MMMM Do YYYY, h:mm:ss'));
this a working demo
with this approach you can craft every custom format:
function italianTimeFormat (dateUTC) {
if (dateUTC) {
let jsDateFormat = new Date(dateUTC)
let fullStringTime = {
day: Number(jsDateFormat.getDate() < 10) ? '0' + jsDateFormat.getDate() : jsDateFormat.getDate(),
month: Number((jsDateFormat.getMonth() + 1)) < 10 ? '0' + (jsDateFormat.getMonth() + 1) : (jsDateFormat.getMonth() + 1),
year: jsDateFormat.getFullYear(),
hours: Number(jsDateFormat.getHours()) < 10 ? '0' + jsDateFormat.getHours() : jsDateFormat.getHours(),
minutes: Number(jsDateFormat.getMinutes()) < 10 ? '0' + jsDateFormat.getMinutes() : jsDateFormat.getMinutes()
}
return fullStringTime.day + '/' + fullStringTime.month + '/' + fullStringTime.year + ' ' +
fullStringTime.hours + ':' + fullStringTime.minutes
}
return null
}
let today = Date.now();
document.write(italianTimeFormat(today))
I hope i've been helpful for someone

How do I get a date in YYYY-MM-DD format?

Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
The problem with doing that, is when I run that code, it returns:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
8/24/2015
Or, maybe MM-DD-YYYY H:M
8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.
var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>
Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way:
var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
By using Moment.js library, you can do:
var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date();
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
//return dd + '/' + mm + '/' + yyyy;
return yyyy + '/' + mm + '/' +dd ;
}
console.log(formatDate(today));
function formatdate(userDate){
var omar= new Date(userDate);
y = omar.getFullYear().toString();
m = omar.getMonth().toString();
d = omar.getDate().toString();
omar=y+m+d;
return omar;
}
console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:
var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM
There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below.
function (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date Get milliseconds from a date.
Ref: Date.prototype.getTimezoneOffset
Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.
date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time)
function UnixTimeToLocalDate = function( unix_epoch_time )
{
var date,
str;
date = new Date( unix_epoch_time * 1000 );
str = date.getFullYear() + '-' +
(date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' +
(date.getDate() + '').padStart( 2, '0' );
// If you need hh:mm:ss too then
str += ' ' +
(date.getHours() + '').padStart( 2, '0' ) + ':' +
(date.getMinutes() + '').padStart( 2, '0' ) + ':' +
(date.getSeconds() + '').padStart( 2, '0' );
return str;
}
If you want a text format that's good for sorting use:
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
As prototype:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01'
new Date().toLocaleDateString("fr-CA",
{year:"numeric", month: "2-digit", day:"2-digit"}
)
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>

Incrementing a date in JavaScript

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)

Categories