Date Format in Javascript(Indonesian Format) [duplicate] - javascript

How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?

You can create one with:-
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(5));
This takes care of automatically incrementing the month if necessary. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.

Correct Answer:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
Proof / Example
Check this JsFiddle
// Correct
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Bad Year/Month
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
// Bad during DST
function addDaysDstFail(date, days) {
var dayms = (days * 24 * 60 * 60 * 1000);
return new Date(date.getTime() + dayms);
}
// TEST
function formatDate(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}
$('tbody tr td:first-child').each(function () {
var $in = $(this);
var $out = $('<td/>').insertAfter($in).addClass("answer");
var $outFail = $('<td/>').insertAfter($out);
var $outDstFail = $('<td/>').insertAfter($outFail);
var date = new Date($in.text());
var correctDate = formatDate(addDays(date, 1));
var failDate = formatDate(addDaysWRONG(date, 1));
var failDstDate = formatDate(addDaysDstFail(date, 1));
$out.text(correctDate);
$outFail.text(failDate);
$outDstFail.text(failDstDate);
$outFail.addClass(correctDate == failDate ? "right" : "wrong");
$outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");
});
body {
font-size: 14px;
}
table {
border-collapse:collapse;
}
table, td, th {
border:1px solid black;
}
td {
padding: 2px;
}
.wrong {
color: red;
}
.right {
color: green;
}
.answer {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th colspan="4">DST Dates</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>03/10/2013</td></tr>
<tr><td>11/03/2013</td></tr>
<tr><td>03/09/2014</td></tr>
<tr><td>11/02/2014</td></tr>
<tr><td>03/08/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr>
<th colspan="4">2013</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2013</td></tr>
<tr><td>02/01/2013</td></tr>
<tr><td>03/01/2013</td></tr>
<tr><td>04/01/2013</td></tr>
<tr><td>05/01/2013</td></tr>
<tr><td>06/01/2013</td></tr>
<tr><td>07/01/2013</td></tr>
<tr><td>08/01/2013</td></tr>
<tr><td>09/01/2013</td></tr>
<tr><td>10/01/2013</td></tr>
<tr><td>11/01/2013</td></tr>
<tr><td>12/01/2013</td></tr>
<tr>
<th colspan="4">2014</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2014</td></tr>
<tr><td>02/01/2014</td></tr>
<tr><td>03/01/2014</td></tr>
<tr><td>04/01/2014</td></tr>
<tr><td>05/01/2014</td></tr>
<tr><td>06/01/2014</td></tr>
<tr><td>07/01/2014</td></tr>
<tr><td>08/01/2014</td></tr>
<tr><td>09/01/2014</td></tr>
<tr><td>10/01/2014</td></tr>
<tr><td>11/01/2014</td></tr>
<tr><td>12/01/2014</td></tr>
<tr>
<th colspan="4">2015</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2015</td></tr>
<tr><td>02/01/2015</td></tr>
<tr><td>03/01/2015</td></tr>
<tr><td>04/01/2015</td></tr>
<tr><td>05/01/2015</td></tr>
<tr><td>06/01/2015</td></tr>
<tr><td>07/01/2015</td></tr>
<tr><td>08/01/2015</td></tr>
<tr><td>09/01/2015</td></tr>
<tr><td>10/01/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr><td>12/01/2015</td></tr>
</tbody>
</table>

var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Be careful, because this can be tricky. When setting tomorrow, it only works because its current value matches the year and month for today. However, setting to a date number like "32" normally will still work just fine to move it to the next month.

These answers seem confusing to me, I prefer:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day.
Hence, ms contains milliseconds for the desired date.
Using the millisecond constructor gives the desired date object.

My simple solution is:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
is correct code.

Here is the way that use to add days, months, and years for a particular date in Javascript.
// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);
// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);
// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);

Try
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.
If you want to just simply add n days to the date you have you are best to just go:
myDate.setDate(myDate.getDate() + n);
or the longwinded version
var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);
This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.

The simplest approach that I have implemented is to use Date() itself.
`
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`

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);

If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Reference: http://momentjs.com/docs/#/manipulating/add/

the simplest answer is, assuming the need is to add 1 day to the current date:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
To explain to you, line by line, what this code does:
Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic

I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}

A solution designed for the pipeline operator:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
Usage:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
If you need more functionality, I suggest looking into the date-fns library.

Without using the second variable, you can replace 7 with your next x days:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));

to substract 30 days use (24h=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=new Date();
var d = new Date(+yourDate - 30 *86400000)
console.log(d)

The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);

You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.

You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;

Short:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(newDate.getDate() + number));
}
console.log({
tomorrow: addDays(new Date(), 1)
});
Advance:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(date.getDate() + number));
}
function addMonths(date, number) {
const newDate = new Date(date);
return new Date(newDate.setMonth(newDate.getMonth() + number));
}
function addYears(date, number) {
const newDate = new Date(date);
return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}
function getNewDate(dateTime) {
let date = new Date();
let number = parseInt(dateTime.match(/\d+/)[0]);
if (dateTime.indexOf('-') != -1)
number = (-number);
if (dateTime.indexOf('day') != -1)
date = addDays(date, number);
else if (dateTime.indexOf('month') != -1)
date = addMonths(date, number);
else if (dateTime.indexOf('year') != -1)
date = addYears(date, number);
return date;
}
console.log({
tomorrow: getNewDate('+1day'),
yesterday: getNewDate('-1day'),
nextMonth: getNewDate('+1month'),
nextYear: getNewDate('+1year'),
});
With fix provide by jperl

Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment

As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000));

Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}

Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}

No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);

I had issues with daylight savings time with the proposed solution.
By using getUTCDate / setUTCDate instead, I solved my issue.
// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
// Make a working copy so we don't mutate the supplied date.
const d = new Date(date);
d.setUTCDate(d.getUTCDate() + num);
return d;
}

Why so complicated?
Let's assume you store the number of days to add in a variable called days_to_add.
Then this short one should do it:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to.
One day is 24h60min60s*1000ms = 86400000 ms or 864E5.

Generic prototype with no variables, it applies on an existing Date value:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}

The mozilla docs for setDate() don't indicate that it will handle end of month scenarios.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
Sets the day of the month (1-31) for a specified date according to local time.
That is why I use setTime() when I need to add days.

I guess I'll give an answer as well:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance. (within reason, of course)
I was going to leave this as just comment under the Answer given by #AnthonyWJones but thought better of it.
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setTime( 864E5 * days + this.valueOf() ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
The above will respect DST. Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.
Example:
Nov 2, 2014 02:00 was the end of DST.
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 09:30:00
If you're looking to retain the time across DST (so 10:30 will still be 10:30)...
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setDate( this.getDate() + days ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
So, now you have...
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 10:30:00

Related

Calculate the difference between two dates and give the result in hh:mm format

date1=2023-01-02T12:22:00
date2=2023-01-03T22:15:00
How could I found the time difference?
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0 ? '-' : '';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0);
}
var d1 = new Date('2023-01-03T22:15:00');
var d2 = new Date('2023-01-02T12:22:00');
//console.log( secondsToHMS((d1 - d2) / 1000)); // 33:53
You can refer to the answer here: https://stackoverflow.com/a/12193371/9067107
The steps are firstly converting the UTC time via new Date() and calculate the different by date1 - date2 and get the Hours / Minutes different.
Lets assume you want to have HH:mm format in string
let date1 = new Date('2023-01-02T12:22:00')
let date2 = new Date('2023-01-03T22:15:00')
let diff = new Date(date2 - date1)
let diffInHoursMinutes = `${diff.getHours()}:${diff.getMinutes()}`

How to add days to a current date and format in JavaScript?

I want to make a function that takes today's date and add more days. For example, if todays' date is 10/09/20 and I add 5 days I want to return 15/09/20.
I want to format the result as such:
15 Sep
I've created the following function:
function calcDate(days){
var curDate = new Date();
var estDate = curDate.setDate(curDate.getDate() + days);
return estDate.getDate() + ' ' + estDate.getMonth();
}
However, I get the error estDate.getDate() is not a function.
If I just return estDate I also get an unformatted number, eg: 1608685587862
I've tried several approaches from Google and Stack Overflow but none work.
Would anyone know what I am to do?
Date.prototype.setDate returns the milliseconds of the result, which is a number, not Date object.
You can also instead add the equivalent milliseconds of those days to the current time to calculate the desired date:
function calcDate(days){
var curDate = new Date();
var estDate = new Date(curDate.getTime() + days * 24 * 60 * 60 * 1000);
return estDate.toLocaleDateString('en-GB', { month: 'short', day: 'numeric' });
}
console.log(calcDate(5));
Almost there! You're using the correct date methods: .setDate(). It's just the formatting that's left.
You can use Moment JS to format the date.
function calcDate(days){
var curDate = new Date();
var estDate = curDate.setDate(curDate.getDate() + days);
return moment(estDate).format('DD/MM/YY');
}
console.log( calcDate( 5 ) );
console.log( calcDate( 10 ) );
console.log( calcDate( 20 ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>
setDate() will return date value in milleseconds, you need to parse it again as date.
In your example you no need to use an additional variable "estdate" you can use the "curDate" variable after you set the date.
Note: Date.getMonth() will return zerobased month i.e. for september it will return 8.
function calcDate(days){
var curDate = new Date();
curDate.setDate(curDate.getDate() + days);
return curDate.getDate() + ' ' + (curDate.getMonth()+1);
}
console.log(calcDate(1));
Here is the Demo (See JavaScript Tab)

how to Add 6 days to current date? [duplicate]

How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?
You can create one with:-
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(5));
This takes care of automatically incrementing the month if necessary. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.
Correct Answer:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
Proof / Example
Check this JsFiddle
// Correct
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Bad Year/Month
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
// Bad during DST
function addDaysDstFail(date, days) {
var dayms = (days * 24 * 60 * 60 * 1000);
return new Date(date.getTime() + dayms);
}
// TEST
function formatDate(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}
$('tbody tr td:first-child').each(function () {
var $in = $(this);
var $out = $('<td/>').insertAfter($in).addClass("answer");
var $outFail = $('<td/>').insertAfter($out);
var $outDstFail = $('<td/>').insertAfter($outFail);
var date = new Date($in.text());
var correctDate = formatDate(addDays(date, 1));
var failDate = formatDate(addDaysWRONG(date, 1));
var failDstDate = formatDate(addDaysDstFail(date, 1));
$out.text(correctDate);
$outFail.text(failDate);
$outDstFail.text(failDstDate);
$outFail.addClass(correctDate == failDate ? "right" : "wrong");
$outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");
});
body {
font-size: 14px;
}
table {
border-collapse:collapse;
}
table, td, th {
border:1px solid black;
}
td {
padding: 2px;
}
.wrong {
color: red;
}
.right {
color: green;
}
.answer {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th colspan="4">DST Dates</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>03/10/2013</td></tr>
<tr><td>11/03/2013</td></tr>
<tr><td>03/09/2014</td></tr>
<tr><td>11/02/2014</td></tr>
<tr><td>03/08/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr>
<th colspan="4">2013</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2013</td></tr>
<tr><td>02/01/2013</td></tr>
<tr><td>03/01/2013</td></tr>
<tr><td>04/01/2013</td></tr>
<tr><td>05/01/2013</td></tr>
<tr><td>06/01/2013</td></tr>
<tr><td>07/01/2013</td></tr>
<tr><td>08/01/2013</td></tr>
<tr><td>09/01/2013</td></tr>
<tr><td>10/01/2013</td></tr>
<tr><td>11/01/2013</td></tr>
<tr><td>12/01/2013</td></tr>
<tr>
<th colspan="4">2014</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2014</td></tr>
<tr><td>02/01/2014</td></tr>
<tr><td>03/01/2014</td></tr>
<tr><td>04/01/2014</td></tr>
<tr><td>05/01/2014</td></tr>
<tr><td>06/01/2014</td></tr>
<tr><td>07/01/2014</td></tr>
<tr><td>08/01/2014</td></tr>
<tr><td>09/01/2014</td></tr>
<tr><td>10/01/2014</td></tr>
<tr><td>11/01/2014</td></tr>
<tr><td>12/01/2014</td></tr>
<tr>
<th colspan="4">2015</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2015</td></tr>
<tr><td>02/01/2015</td></tr>
<tr><td>03/01/2015</td></tr>
<tr><td>04/01/2015</td></tr>
<tr><td>05/01/2015</td></tr>
<tr><td>06/01/2015</td></tr>
<tr><td>07/01/2015</td></tr>
<tr><td>08/01/2015</td></tr>
<tr><td>09/01/2015</td></tr>
<tr><td>10/01/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr><td>12/01/2015</td></tr>
</tbody>
</table>
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Be careful, because this can be tricky. When setting tomorrow, it only works because its current value matches the year and month for today. However, setting to a date number like "32" normally will still work just fine to move it to the next month.
These answers seem confusing to me, I prefer:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day.
Hence, ms contains milliseconds for the desired date.
Using the millisecond constructor gives the desired date object.
My simple solution is:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
is correct code.
Here is the way that use to add days, months, and years for a particular date in Javascript.
// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);
// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);
// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);
Try
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.
Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.
If you want to just simply add n days to the date you have you are best to just go:
myDate.setDate(myDate.getDate() + n);
or the longwinded version
var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);
This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.
The simplest approach that I have implemented is to use Date() itself.
`
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
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);
If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Reference: http://momentjs.com/docs/#/manipulating/add/
the simplest answer is, assuming the need is to add 1 day to the current date:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
To explain to you, line by line, what this code does:
Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
A solution designed for the pipeline operator:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
Usage:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
If you need more functionality, I suggest looking into the date-fns library.
Without using the second variable, you can replace 7 with your next x days:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
to substract 30 days use (24h=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=new Date();
var d = new Date(+yourDate - 30 *86400000)
console.log(d)
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
Short:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(newDate.getDate() + number));
}
console.log({
tomorrow: addDays(new Date(), 1)
});
Advance:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(date.getDate() + number));
}
function addMonths(date, number) {
const newDate = new Date(date);
return new Date(newDate.setMonth(newDate.getMonth() + number));
}
function addYears(date, number) {
const newDate = new Date(date);
return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}
function getNewDate(dateTime) {
let date = new Date();
let number = parseInt(dateTime.match(/\d+/)[0]);
if (dateTime.indexOf('-') != -1)
number = (-number);
if (dateTime.indexOf('day') != -1)
date = addDays(date, number);
else if (dateTime.indexOf('month') != -1)
date = addMonths(date, number);
else if (dateTime.indexOf('year') != -1)
date = addYears(date, number);
return date;
}
console.log({
tomorrow: getNewDate('+1day'),
yesterday: getNewDate('-1day'),
nextMonth: getNewDate('+1month'),
nextYear: getNewDate('+1year'),
});
With fix provide by jperl
Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment
As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000));
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
I had issues with daylight savings time with the proposed solution.
By using getUTCDate / setUTCDate instead, I solved my issue.
// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
// Make a working copy so we don't mutate the supplied date.
const d = new Date(date);
d.setUTCDate(d.getUTCDate() + num);
return d;
}
Why so complicated?
Let's assume you store the number of days to add in a variable called days_to_add.
Then this short one should do it:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to.
One day is 24h60min60s*1000ms = 86400000 ms or 864E5.
Generic prototype with no variables, it applies on an existing Date value:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
Sets the day of the month (1-31) for a specified date according to local time.
That is why I use setTime() when I need to add days.
I guess I'll give an answer as well:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance. (within reason, of course)
I was going to leave this as just comment under the Answer given by #AnthonyWJones but thought better of it.
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setTime( 864E5 * days + this.valueOf() ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
The above will respect DST. Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.
Example:
Nov 2, 2014 02:00 was the end of DST.
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 09:30:00
If you're looking to retain the time across DST (so 10:30 will still be 10:30)...
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setDate( this.getDate() + days ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
So, now you have...
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 10:30:00

How to generate date from current days to last days in Javascript?

I want to generate date as my below PHP code in Javascript But I don't know how to do.
$begin2 = new DateTime(date("Y-m-d", strtotime("-5 day")));
$interval2 = new DateInterval('P1D');
$end2 = new DateTime(date("Y-m-d", strtotime("+1 day")));
$daterange2 = new DatePeriod($begin2, $interval2, $end2);
foreach (array_reverse(iterator_to_array($daterange2)) as $val) {
echo $val->format("Ymd");
}
Output:
2015-12-04
2015-12-03
2015-12-02
2015-12-01
2015-11-30
2015-11-29
2015-11-28
2015-11-27
2015-11-26
2015-11-25
Edit
Wow, completely missed the point of the question!
Seems you want dates from today going backwards for a set number of days in ISO 8601 format. The Date constructor will create a date, and Date.prototype.toISOString will return an ISO 8601 date. It just needs the time part trimmed.
So a function to returns date strings for all the dates from today going back n days is:
function getDateRange(n) {
var d = new Date(),
dates = [];
while (n--) {
dates.push(d.toISOString().split('T')[0]);
d.setDate(d.getDate() - 1);
}
return dates;
}
// Example
document.write(getDateRange(10).join('<br>'));
Original answer
The only reliable way to parse date strings in javascript is to do it manually. A library can help, but a bespoke function isn't much work:
function parseYMD(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
document.write(parseYMD('2015-12-04'))
This assumes the string is a valid date and will parse the string to a local Date, consistent with ECMAScript 2015 (and ISO 8601). If you need to also validate the string, a couple of extra lines are required.
Native "Date" will be enough for some date operations.
var myDate = new Date();
var dateLate = new Date();
var dateEarly = new Date();
dateLate.setDate(dateLate.getDate() + 10);
dateEarly.setDate(dateEarly.getDate() - 10);
myDate.setDate(dateLate.getDate());
while (myDate.getDate() != dateEarly.getDate()) {
myDate.setDate(myDate.getDate() - 1);
document.write(myDate.toLocaleDateString() + '<br>');
}
You can format the date in a different way.
Here's the code doing an iteration in reverse order for your given dates
var now = new Date();
var begin2 = new Date();
var end2 = new Date();
var year, month, day, datestr;
begin2.setDate(now.getDate() - 5);
end2.setDate(now.getDate() + 1);
var current = begin2;
var resulting_dates = [];
while (current <= end2) {
datestr = current.getFullYear() + '-' + ('0' + (current.getMonth() + 1)).slice(-2) + '-' + ('0' + current.getDate()).slice(-2);
resulting_dates.push(datestr);
current.setDate(current.getDate() + 1);
}
console.log(resulting_dates);

JavaScript - get the first day of the week from current date

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - currentDay + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - (currentDay || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
Check out Date.js
Date.today().previous().monday()
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
The solution correctly wraps on months (due to Date.setDate() being used)
For startOfWeek, the same constant numbers as in Date.getDay() can be used
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
It is important to discern between local time and UTC. I wanted to find the start of the week in UTC, so I used the following function.
function start_of_week_utc(date, start_day = 1) {
// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.
date = new Date(date);
const day_of_month = date.getUTCDate();
const day_of_week = date.getUTCDay();
const difference_in_days = (
day_of_week >= start_day
? day_of_week - start_day
: day_of_week - start_day + 7
);
date.setUTCDate(day_of_month - difference_in_days);
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date;
}
To find the start of the week in a given timezone, first add the timezone offset to the input date and then subtract it from the output date.
const local_start_of_week = new Date(
start_of_week_utc(
date.getTime() + timezone_offset_ms
).getTime() - timezone_offset_ms
);
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
Accepted answer won't work for anyone who runs the code in UTC-XX:XX timezone.
Here is code which will work regardless of timezone for date only. This won't work if you provide time too. Only provide date or parse date and provide it as input. I have mentioned different test cases at start of the code.
function getDateForTheMonday(dateString) {
var orignalDate = new Date(dateString)
var modifiedDate = new Date(dateString)
var day = modifiedDate.getDay()
diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
modifiedDate.setDate(diff)
var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
if(diffInDate == 6) {
diff = diff + 7
modifiedDate.setDate(diff)
}
console.log("Given Date : " + orignalDate.toUTCString())
console.log("Modified date for Monday : " + modifiedDate)
}
getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year
Extending answer from #Christian C. Salvadó and information from #Ayyash (object is mutable) and #Awi and #Louis Ameline (set hours to 00:00:00)
The function can be like this
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
d.setDate(diff);
d.setHours(0,0,0,0); // set hours to 00:00:00
return d; // object is mutable no need to recreate object
}
getMonday(new Date())
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too

Categories

Resources