Get the First or Last Friday in a Month
Perhaps it can be made quicker...
This was VERY interesting to code.
Please note that $direction
is 1 for forward and -1 for backward to ease things up :)
Also, $day
begins with a value of 1 for Monday and ends at 7 for Sunday.
function get_date($month, $year, $week, $day, $direction) {
if($direction > 0)
$startday = 1;
else
$startday = date('t', mktime(0, 0, 0, $month, 1, $year));
$start = mktime(0, 0, 0, $month, $startday, $year);
$weekday = date('N', $start);
if($direction * $day >= $direction * $weekday)
$offset = -$direction * 7;
else
$offset = 0;
$offset += $direction * ($week * 7) + ($day - $weekday);
return mktime(0, 0, 0, $month, $startday + $offset, $year);
}
I've tested it with a few examples and seems to work always, be sure to double-check it though ;)
Get last friday of each month in python
The easiest way to do this is to use the module dateutil
:
>>> from dateutil.relativedelta import FR, relativedelta
>>> datetime.date.today()+relativedelta(day=31, weekday=FR(-1))
datetime.date(2021, 6, 25)
Don't assume you can get the last Friday of subsequent months just by adding 28 days. It won't always work. Adding 28 days to the last Friday of February 2024 gives you this:
>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), days=28)
datetime.date(2024, 3, 22)
but the last Friday of that month is 29 March. Let dateutil
do that correctly for you:
>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), months=1)
datetime.date(2024, 3, 29)
How to get the next n fridays which are the first, second or third friday in a month?
You can get the ALIGNED_WEEK_OF_MONTH
temporal field of the local date, and check if it is ≤ 3.
Stream.iterate(now , localDate -> localDate.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)))
.skip(1) // skip today
.filter(x -> x.get(ChronoField.ALIGNED_WEEK_OF_MONTH) <= 3)
.limit(10)
.forEach(System.out::println);
How do we get the date to the last Friday of the month when the last day of the month falls on a weekend
Calculate the day number from the last day of the month.If friday(dayno =5) falls out of 5 then subtract by 5, else add 2 . Then finally subtract the days from the last day of the month if day number is 0 or 6, else return the last day of the month.
var calc = function(monthYear) { var lastDay = moment(monthYear, "MM-YYYY").endOf("month"); var lastDayNumber = lastDay.day(); var daystoSubtract; daystoSubtract = lastDay.day() >= 5 ? (daystoSubtract = lastDayNumber - 5) : (daystoSubtract = lastDayNumber + 2); if (lastDay.day() === 0 || lastDay.day() === 6) { return lastDay.subtract(daystoSubtract, "days"); } else { return lastDay; }};
console.log(calc("05-2020").format("DD-MM-YYYY"));console.log(calc("06-2020").format("DD-MM-YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
How to get the 1st date and last date of the current Week as well as Month in the format of 'yyyy-mm-dd' using App Scripts
You can use toLocaleString("sv-SE") to convert the date to the desired format yyyy-mm-dd
.
Try this:
const today = new Date();
const firstWeekD = today.getDate() - today.getDay()-1;
const lastWeekD = firstWeekD + 6;
const firstdayOfWeek = new Date(today.setDate(firstWeekD)).toLocaleString("sv-SE").slice(0,10);
const lastdayOfWeek = new Date(today.setDate(lastWeekD)).toLocaleString("sv-SE").slice(0,10);
const date = new Date();
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).toLocaleString("sv-SE").slice(0,10);
const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleString("sv-SE").slice(0,10);
console.log(firstdayOfWeek); // first day of the week - Saturday
console.log(lastdayOfWeek); // last day of the week - Friday
console.log(firstDayOfMonth) // first day of the month
console.log(lastDayOfMonth) // last day of the month
How to get first and last day in specific week in month
I found your week calendar approach quite amusing to play with, came up with a method that receives two parameters (month and year) and builds up the week calendar of that month:
private static Map<Integer, Integer[]> getWeekCalendar(int month, int year) {
Map<Integer, Integer[]> weekCalendar = new HashMap<>();
LocalDate date = LocalDate.of(year,month,1);
int week = 1;
LocalDate firstOfWeek = LocalDate.from(date);
while (date.getMonth().equals(Month.of(month))) {
//if it is a saturday, advance to the next week and register current week bounds
if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)) {
weekCalendar.put(week++, new Integer[]{firstOfWeek.getDayOfMonth(), date.getDayOfMonth()});
firstOfWeek = LocalDate.from(date.plusDays(1L));
}
date = date.plusDays(1L);
}
//this one is necessary because the month may end on a Saturday
if (firstOfWeek.getMonth().equals(Month.of(month))) {
weekCalendar.put(week, new Integer[]{firstOfWeek.getDayOfMonth(), date.minusDays(1L).getDayOfMonth()});
}
return weekCalendar;
}
And a main class for testing purposes:
public static void main(String[] args) {
int wantedMonth = 7;
int wantedYear = 2021;
Map<Integer, Integer[]> weekCalendar = getWeekCalendar(wantedMonth, wantedYear);
weekCalendar.entrySet().stream()
.map(e -> String.format("Year %d - Month %d (%s) - Week %d - First day: %d - Last day: %d", wantedYear, wantedMonth, Month.of(wantedMonth).name(), e.getKey(), e.getValue()[0], e.getValue()[1]))
.forEach(System.out::println);
}
output:
Year 2021 - Month 7 (JULY) - Week 1 - First day: 1 - Last day: 3
Year 2021 - Month 7 (JULY) - Week 2 - First day: 4 - Last day: 10
Year 2021 - Month 7 (JULY) - Week 3 - First day: 11 - Last day: 17
Year 2021 - Month 7 (JULY) - Week 4 - First day: 18 - Last day: 24
Year 2021 - Month 7 (JULY) - Week 5 - First day: 25 - Last day: 31
Excel function to determine the last Friday in a month
The following formula achives this for a date in cell A1:
=DATE(YEAR(A1),MONTH(A1)+1,0)+MOD(-WEEKDAY(DATE(YEAR(A1),MONTH(A1)+1,0),2)-2,-7)
How to flag last friday or last day or month
With the additional clarification and following the comment by @eminik the code below
library(data.table)
setDT(data)
data[, LastDayInMonth := day == max(day), by = .(year(day), month(day))]
data[, LastFridayInMonth := weekday == "Friday" & day == max(day),
by = .(year(day), month(day), weekdays(day))]
produces:
# show results (only relevant rows)
data[LastDayInMonth | LastFridayInMonth == TRUE]
day weekday LastDayInMonth LastFridayInMonth
1: 2016-01-29 Friday TRUE TRUE
2: 2016-02-26 Friday FALSE TRUE
3: 2016-02-29 Monday TRUE FALSE
4: 2016-03-25 Friday FALSE TRUE
5: 2016-03-31 Thursday TRUE FALSE
6: 2016-04-29 Friday TRUE TRUE
7: 2016-05-06 Friday FALSE TRUE
8: 2016-05-10 Tuesday TRUE FALSE
Edit: Code modified to account for change of years as requested by OP.
Note: weekdays
returns a character vector of names in the locale in use. Therefore, the code only works if you are in an English locale. Otherwise, you may have to use Sys.setlocale(category = "LC_ALL", locale = "English")
before.
Get Last Friday of Month in Java
Based on marked23's suggestion:
public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
Related Topics
PHP Foreach by Reference Causes Weird Glitch When Going Through Array of Objects
Comma-Separated String to Array
Proper Repository Pattern Design in PHP
Laravel Advanced Wheres How to Pass Variable into Function
How to Paginate a Merged Collection in Laravel 5
Batch Script to Replace PHP Short Open Tags with <Php
Getting All Values from H1 Tags Using PHP
Loadhtml Libxml_Html_Noimplied on an HTML Fragment Generates Incorrect Tags
Trying to Get Property of Non-Object - Codeigniter
Is PHP's 'Include' a Function or a Statement
Invalid JSON Parsing Using PHP
Rest API Authorization & Authentication (Web + Mobile)
Using Wget to Run a Cronjob PHP
How to Set an Arrays Internal Pointer to a Specific Position? PHP/Xml
How to Change Variables in the .Env File Dynamically in Laravel