I would like to know how can we fetch the Last day of the current month using javascript.
E.g. last day of January is Tuesday
var today = new Date()
, lastOfMonth = new Date( today.getFullYear(), today.getMonth()+1, 0 )
, dayOfWeek = lastOfMonth.getDay();
dayOfWeek now = 0 for sunday... 6 for saturday
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 days ago.
I have used js to get the date for the current week displaying the first day of the week (Monday) and the last day of the week (Sunday). This is fine but it displays everything, date, time, timezone, etc. I only want to display the day of the week, the month, and the day's date. I want it to look like Mon Feb 13 and not Mon Feb 13 2023 15:38:09 GMT-0500 (Eastern Standard Time). How would I do it with my current code?
<p class="break"><strong>This class schedule reflects the week <span id="start"></span> - <span id="end"></span></strong></p>
<script type="text/javascript">
const today = new Date();
function getFirstDayOfWeek(d) {
const date = new Date(d);
const day = date.getDay();
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
const firstDay = getFirstDayOfWeek(today);
const lastDay = new Date(firstDay);
lastDay.setDate(lastDay.getDate() + 6);
document.getElementById("start").innerHTML = firstDay;
document.getElementById("end").innerHTML = lastDay;
</script>
I tried to add .getUTCDate() at the end and it didn't work.
Enter your date in new Date(yourdate)
const dateFormat = new Date() .toLocaleString("default", {weekday:"short",month: "short", day: "numeric" });
console.log(dateFormat)
I am trying to get previous week data ..
Suppose I am in current week whether start or end I have to get value of previous week.
Suppose today is 7 Nov Monday.
But I have to get value of Last Sunday 30 Oct (00:00) to 5th Nov Saturday (23:59:59)
So, start date would be 30 oct and end date would be 5th Nov
And tomorrow will be 8 Nov Tuesday but then also
I have to get value of Last Sunday 30 Oct (00:00) and 5th Nov Saturday (23:59:59)
start date would be 31 oct and end date would be 5th Nov,
and it should be dynamic, if week change then again previous week of current week.
I am using below code but from this I am getting current week start and end weekdays
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var last = first + 6;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
You can move the var first to 7 days before then you will get the previous week's first day and last day.
Try out this code.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
first = first - 7
var firstdayOb = new Date(curr.setDate(first));
var firstday = firstdayOb.toUTCString();
var firstdayTemp = firstdayOb;
var lastday = new Date(firstdayTemp.setDate(firstdayTemp.getDate() + 6 )).toUTCString();
console.log(firstday);
console.log(lastday);
I have to find week number of the month from given date using JavaScript. Week start is Monday.
I have tried the code below but not getting accurate result.
function getWeekNumber(date) {
var monthStartDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
monthStartDate = new Date(monthStartDate);
var day = monthStartDate.getDay();
date = new Date(date);
var date = date.getDate();
let weekNumber = Math.ceil((date + (day)) / 7);
return (weekNumber == 0) ? 1 : weekNumber;
}
var week = getWeekNumber('2020-04-04');
console.log(week);
Try this one
function getWeek(date) {
let monthStart = new Date(date);
monthStart.setDate(0);
let offset = (monthStart.getDay() + 1) % 7 - 1; // -1 is for a week starting on Monday
return Math.ceil((date.getDate() + offset) / 7);
}
getWeek(new Date(2019, 2, 14))
You could find the week number of the month for weeks starting on Monday (in line with the ISO week date system) by rolling the input date back to the previous Monday and then dividing the Monday date by 7 and rounding up to determine which week of the month the date falls in.
This approach will properly handle dates at the beginning of a month which actually fall in the last week of the previous month. For instance, 2020-04-04 is a Saturday in the week starting on 2020-03-30 (Monday), so it should return week 5 since it is part of the 5th week of March (and not part of the 1st week of April which starts on 2020-04-06, the first Monday in April).
For example (the split bit at the beginning is just to parse the date string rather than relying on new Date() to parse the string since that is not recommended due to browser inconsistencies):
const monthWeek = (s) => {
const [y, m, d] = s.split('-'); // parse date string
const date = new Date(y, m - 1, d); // create date object
date.setDate(d - ((date.getDay() + 6) % 7)); // adjust date to previous Monday
return Math.ceil(date.getDate() / 7); // return week number of the month
};
console.log(monthWeek('2020-04-04'));
// 5
console.log(monthWeek('2020-04-07'));
// 1
For eg. Date is 2019-01-29 (Jan 29,2019)
I want set month January from 29 Date to 31 Date and display as 2019-01-31 as result using JavaScript
//Set this to whatever date you want..
var d = '2019-02-21';
//Parse out our date object a bit..
var asOf = new Date(d);
var year = asOf.getFullYear();
var month = asOf.getMonth();
//Initially set to first day of next month..
var desiredDate = new Date(year, month + 1, 1);
//Now just subtract 1 day to make it the last day of prior month..
desiredDate.setDate(desiredDate.getDate() - 1);
//Show the date of last day in month..
console.log(`The last day of ${month + 1}/${year} is: ${desiredDate.toLocaleString().split(',')[0]}`);
var date = new Date();
date.setMonth(date.getMonth() + 1);
date.setDate(-1);
Setting date to -1 sets it to the last day of the previous month.
given a date object,how to get previous week's first day
This Datejs library looks like it can do that sort of thing relatively easily.
Code:
function getPreviousSunday()
{
var today=new Date();
return new Date().setDate(today.getDate()-today.getDay()-7);
}
function getPreviousMonday()
{
var today=new Date();
if(today.getDay() != 0)
return new Date().setDate(today.getDate()-7-6);
else
return new Date().setDate(today.getDate()-today.getDay()-6);
}
Reasoning:
Depends what you mean by previous week's first day. I'll assume you mean previous sunday for the sake of this discussion.
To find the number of days to subtract:
Get the current day of the week.
If the current day of the week is Sunday you subtract 7 days
If the current day is Monday you subtract 8 days
...
If the current day is Saturday 13 days
The actual code once you determine the number of days to subtract is easy:
var previous_first_day_of_week=new Date().setDate(today.getDate()-X);
Where X is the above discussed value. This value is today.getDay() + 7
If by first day of the week you meant something else, you should be able to deduce the answer from the above steps.
Note: It is valid to pass negative values to the setDate function and it will work correctly.
For the code about Monday. You have that special case because getDay() orders Sunday before Monday. So we are basically replacing getDay() in that case with a value of getDay()'s saturday value + 1 to re-order sunday to the end of the week.
We use the value of 6 for subtraction with Monday because getDay() is returning 1 higher for each day than we want.
function previousWeekSunday(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 7);
}
function previousWeekMonday(d) {
if(!d.getDay())
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13);
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6);
}
I didn't quite understand other people's posts. Here is the javascript I use to display a Sun-Sat week relative to a given day. So, for instance, to get "last week," you're checking what the Sun/Sat goalposts were relative to seven days ago: new Date()-7
// variables
var comparedate = new Date()-7; // a week ago
var dayofweek = comparedate.getDay();
// just for declaration
var lastdate;
var firstadate;
// functions
function formatDate (dateinput) // makes date "mm/dd/yyyy" string
{
var month = dateinput.getMonth()+1;
if( month < 10 ) { month = '0' + month }
var date = dateinput.getDate();
if( date < 10 ) { var date = '0' + date }
var dateoutput = month + '/' + date + '/' + dateinput.getFullYear();
return dateoutput;
}
// Sunday to Saturday ... Sunday is the firstdate, Saturday is the lastdate
// (modify this block if you want something different eg: Monday to Sunday)
if ( dayofweek == 6 ) { lastdate = comparedate; firstdate = comparedate-6; } // Saturday
else if ( dayofweek == 0 ) { lastdate = comparedate+6; firstdate = comparedate; } // Sunday
else if ( dayofweek == 1 ) { lastdate = comparedate+5; firstdate = comparedate-1; } // Monday
else if ( dayofweek == 2 ) { lastdate = comparedate+4; firstdate = comparedate-2; } // Tuesday
else if ( dayofweek == 3 ) { lastdate = comparedate+3; firstdate = comparedate-3; } // Wednesday
else if ( dayofweek == 4 ) { lastdate = comparedate+2; firstdate = comparedate-4; } // Thursday
else if ( dayofweek == 5 ) { lastdate = comparedate+1; firstdate = comparedate-5; } // Friday
// Finish
var outputtowebpage = formatDate(firstdate) + ' - ' + formatDate(lastdate);
document.write(outputtowebpage);
I have to look this up every time I need to do it. So, I hope this is helpful to others.
First day of week can be either Sunday or Monday depending on what country you are in:
function getPrevSunday(a) {
return new Date(a.getTime() - ( (7+a.getDay())*24*60*60*1000 ));
};
function getPrevMonday(a) {
return new Date(a.getTime() - ( (6+(a.getDay()||7))*24*60*60*1000 ));
};
If you want to set a dateobject to the previous sunday you can use:
a.setDate(a.getDate()-7-a.getDay());
and for the previous monday:
a.setDate(a.getDate()-6-(a.getDay()||7));
In the other examples you will have a problem when sunday falls in other month. This should solve the problem:
var today, todayNumber, previousWeek, week, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
previousWeek = -1; //For every week you want to go back the past fill in a lower number.
week = previousWeek * 7;
mondayNumber = 1 - todayNumber + week;
monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+mondayNumber);