Find first day of previous month in javascript - javascript

Given a date object, how to get its previous month's first day in javascript

function firstDayInPreviousMonth(yourDate) {
var d = new Date(yourDate);
d.setDate(1);
d.setMonth(d.getMonth() - 1);
return d;
}
EDIT: Alright... I've definitely learned something here. I think that this is the simplest solution that covers all cases (and yes, it does work for January):
function firstDayInPreviousMonth(yourDate) {
return new Date(yourDate.getFullYear(), yourDate.getMonth() - 1, 1);
}

The following should work:
now = new Date();
if (now.getMonth() == 0) {
current = new Date(now.getFullYear() - 1, 11, 1);
} else {
current = new Date(now.getFullYear(), now.getMonth() - 1, 1);
}
keeping in mind that months are zero-based so December is 11 rather than 12.
But, as others have pointed out, the month wraps, even as part of the atomic constructor, so the following is also possible:
now = new Date();
firstDayPrevMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);

I like this solution. It might not be the briefest, but it highlights some functions of the setDate() method on Date() objects that not everybody will be familiar with:
function firstDayPreviousMonth(originalDate) {
var d = new Date(originalDate);
d.setDate(0); // set to last day of previous month
d.setDate(1); // set to the first day of that month
return d;
}
It makes use of the fact that .setDate(0) will change the date to point to the last day of the previous month, while .setDate(1) will change it (further) to point to the first day of that month. It lets the core Javascript libs do the heavy lifting.
You can see a working Plunk here.

It will help to get the previous month first and last date.
function getLastMonth(){
var now = new Date();
var lastday = new Date(now.getFullYear(), now.getMonth(), 0);
var firstday = new Date(lastday.getFullYear(), lastday.getMonth(), 1);
var lastMonth = firstday.getDate()+'/'+(firstday.getMonth()+1)+'/'+firstday.getFullYear()+' - '+lastday.getDate()+'/'+(firstday.getMonth()+1)+'/'+lastday.getFullYear();
return lastMonth;
}

Why reinventing the wheel?
Use moment.js or one of the alternatives (Luxon, Day.js, etc.):
moment().subtract(1, "months").startOf("months").toDate().

I've needed to use the begging of the month in a BootStrap Min month and didn't want to write it all out.
(() => new Date(new Date().getFullYear(), new Date().getMonth(),1, 0))()

Related

How to reliably get previous month from js Date?

What's the better way to get the previous month from a given day in vanilla javascript?
A quick search would tell you to do:
const getPreviousMonth = date => {
const clone = new Date(date.getTime())
clone.setMonth(date.getMonth() - 1)
return clone
}
The problem being getPreviousDate(new Date(2021, 4, 31)) returns May 1st, not April 30, which seems to imply it just subtracts 30 days. Curiously, getPreviousDate(new Date(2021, 2, 1)) correctly return Feb 1st instead of a late date in January, so the 30 days theory is a dud.
Given that, is there a best practice vanilla solution to getPrevious month? Currently, I add a line like: if (date.getDate() === 31) newDate.setDate(-1) which returns April 29 (!?). So I'm sure a better solutions exists.
PS.: Just to be clear, I don't want to know what date it was 30 days ago, but what month was the previous month. So to May 31 the answer is April, to March 1, it is February.
Edit: Specifically, I want to return a Date object within the previous month, preferably on the last day.
Just use clone.setDate(0) and you will get the last day of previous month
const dates = [new Date(2021,0,15), new Date(2021,2,31)]
const getPreviousMonth = date => {
const clone = new Date(date)
clone.setDate(0)
return clone
}
dates.forEach(d=>{
console.log(getPreviousMonth(d))
})
Is that what you are looking for:
now = new Date();
if (now.getMonth() == 0) {
var current = new Date(now.getFullYear() - 1, 11, 1);
} else {
var current = new Date(now.getFullYear(), now.getMonth());
}
console.log(current);

Error incrementing days to a specific date

I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);
However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?
Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.
new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.
it should be like,
date.setDate(date.getDate() + 1);
if you can't change the original date object, then it can be done like this,
var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);
nextDay is one day after date:
var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);
Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.

Javascript: setDate(DATE + day) not update month

I created this function to increment a date (for a jQuery UI Datepicker):
function addDay(date) {
var moreDay = new Date();
var decomposed = date.split("-");
var act = new Date(decomposed[2], decomposed[1], decomposed[0]);
moreDay.setDate(act.getDate()+1);
return moreDay;
}
So, it scomposes the date (ex: 12-06-2013 (dd-mm-YYYY)) and put the values into a new Date, after that it addes a day. It works, but the month not change. Example, I changed the function into this:
function addDay() {
var moreDay = new Date();
var act = new Date(2013, 7, 3);
moreDay.setDate(act.getDate()+1);
alert(moreDay);
}
And it returns Jun 4th 2013.. How it's possible?
I think I see what's the trouble.
function addDay() {
var moreDay = new Date();
var act = new Date(2013, 7, 3);
moreDay.setDate(act.getDate()+1);
alert(moreDay);
}
And it returns Jun 4th 2013.. How it's possible?
Some points you must consider:
The creation of the date new Date(2013, 7, 3) does not create the date 03/Jul/2013:
Months are zero-based, meaning they go from 0 to 11, not 1 to 12.
This way, the month 7 actually is August.
The statement moreDay.setDate(act.getDate()+1) does not make moreDay the date act plus one day. Because:
date.getDate() returns the day of the month of the date variable
date.setDate(int) sets the day of date (just the day, leaving the year and month intact)
What the statement moreDay.setDate(act.getDate()+1) does then is:
Set moreDay's day the value of act's day plus one.
In other words, as moreDay's value is new Date() (which is the current day - right now 11/Jun/2013 where I live), and act's day is 3, the statement evaluation then really is:
Step #1: moreDay.setDate( act.getDate() + 1 );
Step #2: moreDay.setDate( (03/Aug/2013).getDate() + 1 );
Step #3: moreDay.setDate( 03 + 1 );
Step #4: moreDay.setDate( 4 );
Step #5: (11/Jun/2013).setDate( 4 );
Step #6: (04/Jun/2013)
Thus ending Jun 4th 2013.
It's not clear what you want to do with your function. If you want to take a date and add a day, try with this:
function addDay(date) {
var decomposed = date.split("-"),
moreDay = new Date(decomposed[2], decomposed[1] - 1, decomposed[0]);
moreDay.setDate(moreDay.getDate() + 1);
alert(moreDay);
}
Please take note that in common dd-mm-yyyy dates, January is 1, whereas to define a Date object January is 0, hence the - 1.
This alternative should be faster than setDate:
moreDay.setTime(moreDay.getTime() + 864e5);
Or you could define your Date object directly with an added day:
moreDay = new Date(decomposed[2], decomposed[1] - 1, +decomposed[0] + 1);
moreDay.setDate(act.getDate()+1);
This will only add one day. Why do you expect it to add a month, too?
If you want to add a month also, try this:
function addDay() {
var moreDay = new Date();
var act = new Date(2013, 7, 3);
moreDay.setMonth(act.getMonth()+1); // add one month
moreDay.setDate(act.getDate()+1); // add one day
alert(moreDay);
}
One way to do this:
var now = new Date();
function addDays(date,days) {
var currentDate = date.getDate();
date.setDate(currentDate + days);
alert(date);
}
addDays(now,14)

Get the most recently occurring Sunday

I need to display the current week in a calendar view, starting from Sunday.
What's the safest way to determine "last sunday" in Javascript?
I was calculating it using the following code:
Date.prototype.addDays = function(n) {
return new Date(this.getTime() + (24*60*60*1000)*n);
}
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = today.addDays(0-today.getDay());
This code makes the assumption that every day consists of twenty four hours. This is correct, EXCEPT if it's a daylight savings crossover day, in which case the day could be twenty-three or twenty-five hours.
This week, In Sydney, Australia, we set our clocks forward an hour. As a result, my code calculates lastSunday as 23:00 on Saturday.
So what IS the safest and most efficient way to determine last Sunday?
To safely add exactly one day, use:
d.setDate(d.getDate() + 1);
which is daylight saving safe. To set a date object to the last Sunday:
function setToLastSunday(d) {
return d.setDate(d.getDate() - d.getDay());
}
Or to return a new Date object for last Sunday:
function getLastSunday(d) {
var t = new Date(d);
t.setDate(t.getDate() - t.getDay());
return t;
}
Edit
The original answer had an incorrect version adding time, that does add one day but not how the OP wants.
Try this jsfiddle
It uses only built in date methods
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = new Date(today.setDate(today.getDate()-today.getDay()));
using date-fn library: previousSunday(date)
const now = new Date(); // the date to start counting from
previousSunday(now);
Docs: https://date-fns.org/v2.25.0/docs/previousSunday

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

I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.
It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.
What's the simplest way of doing this?
[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]
var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
day.setDate(day.getDate() -1); //will be wrong
this will return wrong day. under UTC -03:00, check for
var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17
Better use:
var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything
getDate()-1 should do the trick
Quick example:
var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
console.log(decrementedDate);
setDate(dayValue)
dayValue is an integer from 1 to 31, representing the day of the month.
from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate
The behaviour solving your problem (and mine) seems to be out of specification range.
What seems to be needed are addDate(), addMonth(), addYear() ... functions.
Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.
To subtract one day:
const date = moment().subtract(1, 'day')

Categories