Last Friday of each month: Difference between revisions

Added Easylang
(Added Algol W)
(Added Easylang)
 
(41 intermediate revisions by 23 users not shown)
Line 33:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Last Friday of each month 17/07/2016
LASTFRI CSECT
USING LASTFRI,R13 base register
Line 111:
DW DS D packed (PL8) 15num
YREGS
END LASTFRI</langsyntaxhighlight>
{{out}}
<pre>
Line 126:
2016-11-25
2016-12-30
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752
BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
BYTE res
 
IF m<3 THEN
y==-1
FI
res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7
RETURN (res)
 
BYTE FUNC IsLeapYear(INT y)
IF y MOD 100=0 THEN
IF y MOD 400=0 THEN
RETURN (1)
ELSE
RETURN (0)
FI
FI
IF y MOD 4=0 THEN
RETURN (1)
FI
RETURN (0)
 
INT FUNC GetMaxDay(INT y BYTE m)
BYTE ARRAY MaxDay=[31 28 31 30 31 30 31 31 30 31 30 31]
 
IF m=2 AND IsLeapYear(y)=1 THEN
RETURN (29)
FI
RETURN (MaxDay(m-1))
 
PROC PrintB2(BYTE x)
IF x<10 THEN
Put('0)
FI
PrintB(x)
RETURN
 
PROC Main()
INT MinYear=[1753],MaxYear=[9999],y
BYTE m,d,last,maxD
 
DO
PrintF("Input year in range %I...%I: ",MinYear,MaxYear)
y=InputI()
UNTIL y>=MinYear AND y<=MaxYear
OD
 
FOR m=1 TO 12
DO
last=0
maxD=GetMaxDay(y,m)
FOR d=1 TO maxD
DO
IF DayOfWeek(y,m,d)=5 THEN
last=d
FI
OD
PrintI(y) Put('-)
PrintB2(m) Put('-)
PrintB2(last) PutE()
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Last_Friday_of_each_month.png Screenshot from Atari 8-bit computer]
<pre>
Input year in range 1753...9999: 2021
2021-01-29
2021-02-26
2021-03-26
2021-04-30
2021-05-28
2021-06-25
2021-07-30
2021-08-27
2021-09-24
2021-10-29
2021-11-26
2021-12-31
</pre>
 
Line 132 ⟶ 216:
Uses GNAT. Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Find_last_sunday_of_each_month#Ada]].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, GNAT.Calendar.Time_IO, Ada.Command_Line,
Ada.Calendar.Formatting, Ada.Calendar.Arithmetic;
 
Line 161 ⟶ 245:
Put_Line(Selected);
end loop;
end Last_Weekday_In_Month;</langsyntaxhighlight>
{{out}}
<pre>>./last_weekday_in_month friday 2012
Line 176 ⟶ 260:
2012-11-30
2012-12-28</pre>
 
=={{header|ALGOL 68}}==
Basically the same as the "Find the Last Sunday Of Each Month" task solution.
{{Trans|ALGOL W}}
<syntaxhighlight lang="algol68">BEGIN # find the last Friday in each month of a year #
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
PROC is leap year = ( INT year )BOOL:
year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 );
# returns the day of the week of the specified date (d/m/y) #
# Sunday = 1 #
PROC day of week = ( INT d, m, y )INT:
BEGIN
INT mm := m;
INT yy := y;
IF mm <= 2 THEN
mm := mm + 12;
yy := yy - 1
FI;
INT j = yy OVER 100;
INT k = yy MOD 100;
(d + ( ( mm + 1 ) * 26 ) OVER 10 + k + k OVER 4 + j OVER 4 + 5 * j ) MOD 7
END # day of week # ;
# returns an array of the last Friday of each month in year #
PROC last fridays = ( INT year )[]INT:
BEGIN
[ 1 : 12 ]INT last days := ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
IF is leap year( year ) THEN last days[ 2 ] := 29 FI;
# for each month, determine the day number of the #
# last Friday #
[ 1 : 12 ]INT last;
FOR m pos TO 12 DO
INT dow := day of week( last days[ m pos ], m pos, year );
# dow = 1 Sun, 2 Mon, ... , 6 Fri, 0 Sat #
# change to 2 Sun, 3 Mon, ... , 0 Fri, 1 Sat #
dow := ( dow + 1 ) MOD 7;
# offset the last day to the last Friday #
last[ m pos ] := last days[ m pos ] - dow
OD;
last
END # last fridays # ;
# test the last fridays procedure #
INT year = 2021;
[]INT last = last fridays( year );
FOR m pos TO 12 DO
print( ( whole( year, 0 )
, IF m pos < 10 THEN "-0" ELSE "-1" FI
, whole( m pos MOD 10, 0 )
, "-"
, whole( last[ m pos ], 0 )
, newline
)
)
OD
END</syntaxhighlight>
{{out}}
<pre>
2021-01-29
2021-02-26
2021-03-26
2021-04-30
2021-05-28
2021-06-25
2021-07-30
2021-08-27
2021-09-24
2021-10-29
2021-11-26
2021-12-31
</pre>
 
=={{header|ALGOL W}}==
Basically the same as the "Find the Last Sunday Of Each Month" task solution, uses the Day_of_week and isLeapYear procedures from the the day-of-the-week and leap-year tasks (included here for convenience).
<langsyntaxhighlight lang="algolw">begin % find the last Friday in each month of a year %
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
Line 236 ⟶ 390:
for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 256 ⟶ 410:
 
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- LAST FRIDAYS OF YEAR ------------------------------------------------------
 
-- lastFridaysOfYear :: Int -> [Date]
Line 451 ⟶ 605:
map(column, item 1 of xss)
end transpose</langsyntaxhighlight>
{{Out}}
<pre>2014-01-31 2015-01-30 2016-01-29 2017-01-27 2018-01-26
Line 472 ⟶ 626:
AppleScript's weekday constants can be coerced either to English text or to the integers 1 (for Sunday) to 7 (Saturday).
 
<langsyntaxhighlight AppleScriptlang="applescript">on lastFridayOfEachMonthInYear(y)
-- Initialise an AppleScript date to the first day of some month in the specified year.
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 494 ⟶ 648:
end lastFridayOfEachMonthInYear
 
lastFridayOfEachMonthInYear(2020)</langsyntaxhighlight>
 
{{Out}}
Line 513 ⟶ 667:
The above is of course hard-coded for Fridays. It can be made more flexible by taking an AppleScript weekday constant as a parameter:
 
<langsyntaxhighlight AppleScriptlang="applescript">on lastWeekdayWOfEachMonthInYear(w, y) -- Parameters: (AppleScript weekday constant, AD year number)
-- Initialise an AppleScript date to the first day of some month in the specified year.
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 537 ⟶ 691:
end lastWeekdayWOfEachMonthInYear
 
lastWeekdayWOfEachMonthInYear(Friday, 2020)</langsyntaxhighlight>
{{Out}}
<pre>"./last_Fridays 2020
Line 555 ⟶ 709:
=={{header|Arturo}}==
 
<langsyntaxhighlight arturolang="rebol">lastFridayForMonth: @(function [m){][
ensure -> in? m 1..12
if [contains #(1 3 5 7 8 10 12) m] -> nofDays: 31
if [contains #(4 6 9 11) m] -> nofDays: 30
if m=2 -> nofDays: 27
 
daysOfMonth: [0 31 27 31 30 31 30 31 31 30 31 30 31]
loop nofDays..1 @(d){
loop range get daysOfMonth m 1 [d][
dt: datetime "2012-"+m+"-"+d "yyyy-M-dd"
dt: to :date.format:"yyyy-M-dd" ~"2012-|m|-|d|"
if [day dt]="Friday" -> return dt
if dt\Day = "Friday" -> return dt
}
]
}
]
 
loop 1..12 -> print [datetime [lastFridayForMonth &] "yyyy-MM-dd"]</lang>
loop 1..12 'month [
print to :string.format:"yyyy-MM-dd" lastFridayForMonth month
]</syntaxhighlight>
 
{{out}}
Line 584 ⟶ 739:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">if 1 = ; no parameter passed
{
InputBox, 1, Last Fridays of year, Enter a year:, , , , , , , , %A_YYYY%
Line 612 ⟶ 767:
stmp += 1, days
}
MsgBox % res</langsyntaxhighlight>
{{out}} for 2012:
<pre>2012-01-27
Line 629 ⟶ 784:
=={{header|AutoIt}}==
 
<syntaxhighlight lang="autoit">
<lang AutoIt>
#include <Date.au3>
 
Line 652 ⟶ 807:
ConsoleWrite($sResult)
EndFunc ;==>_GetFridays
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 672 ⟶ 827:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LAST_FRIDAY_OF_EACH_MONTH.AWK year
# converted from Fortran
Line 690 ⟶ 845:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 706 ⟶ 861:
2012-12-28
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$ + "DATELIB"
 
INPUT "What year to calculate (YYYY)? " Year%
 
PRINT '"Last Fridays in ";Year% " are on:"
FOR Month%=1 TO 12
PRINT Year% "-" RIGHT$("0" + STR$Month%, 2) "-"; \
\ FN_dim(Month%, Year%) - (FN_dow(FN_mjd(FN_dim(Month%, Year%), Month%, Year%)) + 2) MOD 7
NEXT</syntaxhighlight>
{{out}}
<pre>What year to calculate (YYYY)? 2023
 
Last Fridays in 2023 are on:
2023-01-27
2023-02-24
2023-03-31
2023-04-28
2023-05-26
2023-06-30
2023-07-28
2023-08-25
2023-09-29
2023-10-27
2023-11-24
2023-12-29</pre>
 
=={{header|Befunge}}==
Line 711 ⟶ 894:
The algorithm has been slightly simplified to avoid the additional day adjustment inside the loop, and the year is obtained from stdin rather than via the command line.
 
<langsyntaxhighlight lang="befunge">":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v
v2++1**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5<
>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v
^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6
>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8
^<# #"#"##"#"##!` +76:+1g00,+55,+*<</langsyntaxhighlight>
 
{{out}}
Line 737 ⟶ 920:
Doesn't work with Julian calendar (then again, you probably don't need to plan your weekends for middle ages).
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 756 ⟶ 939:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Globalization;
Line 796 ⟶ 979:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>01/27/2012
Line 814 ⟶ 997:
{{libheader|Boost}}
called with <code>./last_fridays 2012</code>
<langsyntaxhighlight lang="cpp">#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <cstdlib>
Line 830 ⟶ 1,013:
}
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>2012-Jan-27
Line 844 ⟶ 1,027:
2012-Nov-30
2012-Dec-28
</pre>
===Using C++20===
Using C++20 this task can be completed without external libraries.
<syntaxhighlight lang="c++">
 
#include <chrono>
#include <iostream>
 
int main() {
std::cout << "The dates of the last Friday in each month of 2023:" << std::endl;
 
for ( unsigned int m = 1; m <= 12; ++m ) {
std::chrono::days days_in_month = std::chrono::sys_days{std::chrono::year{2023}/m/std::chrono::last}
- std::chrono::sys_days{std::chrono::year{2023}/m/1} + std::chrono::days{1};
 
const unsigned int last_day = days_in_month / std::chrono::days{1};
std::chrono::year_month_day ymd{std::chrono::year{2023}, std::chrono::month{m}, std::chrono::day{last_day}};
 
while ( std::chrono::weekday{ymd} != std::chrono::Friday ) {
ymd = std::chrono::sys_days{ymd} - std::chrono::days{1};
}
 
std::cout << ymd << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
The dates of the last Friday in each month of 2023:
2023-01-27
2023-02-24
2023-03-31
2023-04-28
2023-05-26
2023-06-30
2023-07-28
2023-08-25
2023-09-29
2023-10-27
2023-11-24
2023-12-29
</pre>
 
Line 849 ⟶ 1,073:
{{libheader|clj-time}}
 
<langsyntaxhighlight lang="clojure">(use '[clj-time.core :only [last-day-of-the-month day-of-week minus days]]
'[clj-time.format :only [unparse formatters]])
 
Line 859 ⟶ 1,083:
 
(defn last-fridays-formatted [year]
(sort (map #(unparse (formatters :year-month-day) %) (last-fridays year))))</langsyntaxhighlight>
 
{{out}}
Line 877 ⟶ 1,101:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. last-fri.
data division.
Line 926 ⟶ 1,150:
.
end program last-fri.
</syntaxhighlight>
</lang>
 
{{out}}
Line 945 ⟶ 1,169:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
last_friday_of_month = (year, month) ->
# month is 1-based, JS API is 0-based, then we use
Line 964 ⟶ 1,188:
year = parseInt process.argv[2]
print_last_fridays_of_month year
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
> coffee last_friday.coffee 2012
Fri Jan 27 2012
Line 980 ⟶ 1,204:
Fri Nov 30 2012
Fri Dec 28 2012
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 986 ⟶ 1,210:
The command-line argument processing is the only CLISP-specific code.
 
<langsyntaxhighlight lang="lisp">(defun friday-before (year month day)
(let*
((timestamp (encode-universal-time 0 0 12 day month year))
Line 999 ⟶ 1,223:
 
(let* ((year (read-from-string (car *args*))))
(format t "~{~{~a-~2,'0d-~2,'0d~}~%~}" (last-fridays year)))</langsyntaxhighlight>
 
Sample run for the year 2015:
Line 1,017 ⟶ 1,241:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.datetime, std.traits;
 
void lastFridays(in uint year) {
Line 1,031 ⟶ 1,255:
void main() {
lastFridays(2012);
}</langsyntaxhighlight>
<pre>2012-Jan-27
2012-Feb-24
Line 1,047 ⟶ 1,271:
=={{header|Delphi}}==
Uses the standard Delphi library.
<langsyntaxhighlight lang="delphi">program LastFridayOfMonth;
 
{$APPTYPE CONSOLE}
Line 1,073 ⟶ 1,297:
WriteLn(DateToStr(D1));
end;
end.</langsyntaxhighlight>
{{out}}
<pre>Enter year: 2019
Line 1,088 ⟶ 1,312:
29.11.2019
27.12.2019</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func leap year .
return if year mod 4 = 0 and (year mod 100 <> 0 or year mod 400 = 0)
.
func weekday year month day .
normdoom[] = [ 3 7 7 4 2 6 4 1 5 3 7 5 ]
c = year div 100
r = year mod 100
s = r div 12
t = r mod 12
c_anchor = (5 * (c mod 4) + 2) mod 7
doom = (s + t + (t div 4) + c_anchor) mod 7
anchor = normdoom[month]
if leap year = 1 and month <= 2
anchor = (anchor + 1) mod1 7
.
return (doom + day - anchor + 7) mod 7 + 1
.
mdays[] = [ 31 28 31 30 31 30 31 31 30 31 30 31 ]
proc last_fridays year . .
for m to 12
d = mdays[m]
if m = 2 and leap year = 1
d = 29
.
d -= (weekday year m d - 6) mod 7
m$ = m
if m < 10
m$ = "0" & m
.
print year & "-" & m$ & "-" & d
.
.
last_fridays 2023
</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def lastFriday(year) do
Enum.map(1..12, fn month ->
Line 1,104 ⟶ 1,365:
Enum.each(RC.lastFriday(y), fn {year, month, day} ->
:io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
end)</langsyntaxhighlight>
 
{{out}}
Line 1,123 ⟶ 1,384:
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">import Html exposing (Html, Attribute, text, div, input)
import Html.App exposing (beginnerProgram)
import Html.Attributes exposing (placeholder, value, style)
Line 1,189 ⟶ 1,450:
, view = view
, update = update
}</langsyntaxhighlight>
Link to live demo: http://dc25.github.io/lastFridayOfMonthElm/
 
Line 1,207 ⟶ 1,468:
December 26, 2003
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(require 'calendar)
 
(defun last-friday (year)
"Print the last Friday in each month of year"
(mapcar (lambda (month)
(let*
((days (number-sequence 1 (calendar-last-day-of-month month year)))
(mdy (mapcar (lambda (x) (list month x year)) days))
(weekdays (mapcar #'calendar-day-of-week mdy))
(lastfriday (1+ (cl-position 5 weekdays :from-end t))))
(insert (format "%i-%02i-%02i \n" year month lastfriday))))
(number-sequence 1 12)))
 
(last-friday 2012)</syntaxhighlight>
{{output}}
<pre>2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28 </pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( last_date_each_month ).
 
Line 1,228 ⟶ 1,518:
Months_days = [{X, Y} || X <- Months, Y <- lists:seq(calendar:last_day_of_the_month(Year, X), calendar:last_day_of_the_month(Year, X) - 7, -1), calendar:valid_date(Year, X, Y), calendar:day_of_the_week(Year, X, Y) =:= Week_day],
[{Year, X, proplists:get_value(X, Months_days)} || X <- Months].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,249 ⟶ 1,539:
{{works with|Factor|0.98}}
The <code>last-friday-of-month</code> word in the <code>calendar</code> vocabulary does most of the work. This program expects the year as a command line argument.
<langsyntaxhighlight lang="factor">USING: calendar calendar.format command-line io kernel math.parser sequences ;
IN: rosetta-code.last-fridays
 
(command-line) second string>number <year> 12 <iota>
[ months time+ last-friday-of-month ] with map
[ timestamp>ymd print ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,275 ⟶ 1,565:
 
Algorithm: compute day of week for last day of month, then subtract just enough to get to the preceding friday. Do this for each month. To simplify computations further, we only need to compute day of week of january 1st (the others are found by adding month lengths). Since day of week need only be known modulo 7, we do not compute modulo at all except once when subtracting.
<langsyntaxhighlight lang="fortran">program fridays
implicit none
integer :: days(1:12) = (/31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31/)
Line 1,288 ⟶ 1,578:
end do
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBasiclang="freebasic">' version 23-06-2015
' compile with: fbc -s console
 
Line 1,375 ⟶ 1,665:
 
Loop
End</langsyntaxhighlight>
{{out}}
<pre>For what year do you want to find the last Friday of the month
Line 1,393 ⟶ 1,683:
24 November
29 December</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">d = parseDate[ARGS@0]
for m = 1 to 12
{
d = beginningOfNextMonth[d]
n = d - (((parseInt[d -> ### u ###] + 1) mod 7) + 1) days
println[n -> ### yyyy-MM-dd ###]
}</syntaxhighlight>
 
{{out}}
<pre>2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Last_day_of_each_month_of_a_year%2C_being_a_given_weekday}}
 
'''Solution'''
 
The following function retrieves the last day of each month of a year, being a given weekday:
 
[[File:Fōrmulæ - Last day of each month of a year, being a given weekday 01.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Last day of each month of a year, being a given weekday 04.png]]
 
[[File:Fōrmulæ - Last day of each month of a year, being a given weekday 05.png]]
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim siYear As Short = InputBox("Please input a year", "Last Friday of each month")
Dim siMonth, siDay As Short
Line 1,414 ⟶ 1,744:
Me.Close
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,432 ⟶ 1,762:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,453 ⟶ 1,783:
fmt.Println(d.Format("2006-01-02"))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,475 ⟶ 1,805:
 
Test:
<langsyntaxhighlight lang="groovy">def ymd = { it.format('yyyy-MM-dd') }
def lastFridays = lastWeekDays.curry(Day.Fri)
lastFridays(args[0] as int).each { println (ymd(it)) }</langsyntaxhighlight>
 
Execution (Cygwin on Windows 7):
Line 1,497 ⟶ 1,827:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Time.Calendar
(Day, addDays, showGregorian, fromGregorian, gregorianMonthLength)
import Data.Time.Calendar.WeekDate (toWeekDate)
Line 1,522 ⟶ 1,852:
mapM_
putStrLn
(intercalate " " <$> transpose (weekDayDates 5 <$> [2012 .. 2017]))</langsyntaxhighlight>
{{Out}}
<pre>2012-01-27 2013-01-25 2014-01-31 2015-01-30 2016-01-29 2017-01-27
Line 1,539 ⟶ 1,869:
=={{header|Icon}} and {{header|Unicon}}==
This will write the last fridays for every year given as an argument. There is no error checking on the year.
<langsyntaxhighlight Iconlang="icon">procedure main(A)
every write(lastfridays(!A))
end
Line 1,558 ⟶ 1,888:
end
 
link datetime, printf</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,581 ⟶ 1,911:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require 'dates'
last_fridays=: 12 {. [: ({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1</langsyntaxhighlight>
 
In other words, start from January 1 of the given year, and count forward for 366 days, keeping the Fridays. Then pick the last remaining day within each represented month (which will be a Friday because we only kept the Fridays). Then pick the first 12 (since on a non-leap year which ends on a Thursday we would get an extra Friday).
Line 1,588 ⟶ 1,918:
Example use:
 
<langsyntaxhighlight lang="j"> last_fridays 2012
2012 1 27
2012 2 24
Line 1,600 ⟶ 1,930:
2012 10 26
2012 11 30
2012 12 28</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.text.*;
import java.util.*;
 
Line 1,629 ⟶ 1,959:
}
}
}</langsyntaxhighlight>
{{out}} (for <code>java LastFridays 2012</code>):
<pre>2012 Jan 27
Line 1,644 ⟶ 1,974:
2012 Dec 28</pre>
 
=={{header|JavaScript}}==
 
==JavaScript==
===ES5===
====Iteration====
{{works with|Nodejs}}
<langsyntaxhighlight lang="javascript">var last_friday_of_month, print_last_fridays_of_month;
 
last_friday_of_month = function(year, month) {
Line 1,676 ⟶ 2,005:
year = parseInt(process.argv[2]);
return print_last_fridays_of_month(year);
})();</langsyntaxhighlight>
{{Out}}
<pre>>node lastfriday.js 2015
Line 1,691 ⟶ 2,020:
Fri Nov 27 2015
Fri Dec 25 2015</pre>
 
 
====Functional composition====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,764 ⟶ 2,092:
})
.join('\n');
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,781 ⟶ 2,109:
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ------------ LAST FRIDAY OF EACH MONTH ------------
<lang JavaScript>(() => {
'use strict'
 
// lastWeekDaysOfYear :: Int -> Int -> [Date]
const lastWeekDaysOfYear = (iWeekDay, y) => [
y => 31,{
0const ===isLeap y % 4 && 0 !== y % 100 || 0n === y % 400 ? 29 :> 28,(
31, 30, 31, 30, 31,(0 31,=== 30,n 31,% 30,4) 31&& (0 !== n % 100)) || (
] 0 === y % 400
.map((d, m) => );
 
new Date(Date.UTC(
return y, m, d - ((new Date(Date.UTC(y, m, d))[
.getDay31, isLeap(y) +? (729 -: iWeekDay)) % 7))));28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
]
.map((d, m) =>
new Date(Date.UTC(
y, m, d - ((
new Date(Date.UTC(
y, m, d
))
.getDay() + (7 - iWeekDay)
) % 7)
))
);
};
 
 
const days = {
Line 1,806 ⟶ 2,149:
};
 
// ---------------------- TEST -----------------------
// GENERIC FUNCTIONS
const main = () =>
transpose(
enumFromTo(2015)(2019)
.map(lastWeekDaysOfYear(days.friday))
)
.map(
row => row.map(isoDateString).join("\t")
)
.join("\n");
 
 
// ---------------- GENERIC FUNCTIONS ----------------
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// isoDateString :: Date -> String
Line 1,816 ⟶ 2,175:
.substr(0, 10);
 
// range :: Int -> Int -> [Int]
const range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
 
// transpose :: [[a]] -> [[a]]
const transpose = lstrows =>
// The columns of the input transposed
lst[0].map((_, iCol) =>
// into new lstrows.map(row => row[iCol]));
0 < rows.length ? rows[0].map(
(x, i) => rows.flatMap(
v => v[i]
)
) : [];
 
// TESTMAIN ---
return transposemain();
})();</syntaxhighlight>
range(2015, 2019)
.map(curry(lastWeekDaysOfYear)(days.friday))
)
.map(row => row
.map(isoDateString)
.join('\t'))
.join('\n');
})();</lang>
{{Out}}
<pre>2015-01-30 2016-01-29 2017-01-27 2018-01-26 2019-01-25
Line 1,854 ⟶ 2,206:
{{ works with|jq|1.4}}
'''Foundations'''
<langsyntaxhighlight lang="jq"># In case your jq does not have "until" defined:
 
def until(cond; next):
Line 1,880 ⟶ 2,232:
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
else . % 7
end ;</langsyntaxhighlight>
'''findLastFridays'''
<langsyntaxhighlight lang="jq"># year and month are numbered conventionally
def findLastFriday(year; month):
def isLeapYear:
Line 1,903 ⟶ 2,255:
(range(0;12) | "\(months[.]) \(findLastFriday($year; .+1))") ;
 
$year|tonumber|findLastFridays</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq --arg year 2012 -n -r -f findLastFridays.jq
YEAR: 2012
January 27
Line 1,918 ⟶ 2,270:
October 26
November 30
December 28</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">using Dates
 
const wday = Dates.Fri
Line 1,946 ⟶ 2,298:
end
end
</langsyntaxhighlight>{{out}}
<pre>
This script will print the last Fridays of each month of the year given.
Line 1,973 ⟶ 2,325:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
/ List the dates of last Fridays of each month of
/ a given year
Line 1,987 ⟶ 2,339:
main: {[y]; lfd1[y];`0: ,"Dates of last Fridays of ",($y);12 10#arr}
 
</syntaxhighlight>
</lang>
The output of a session is given below:
 
Line 2,013 ⟶ 2,365:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.util.*
Line 2,035 ⟶ 2,387:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,056 ⟶ 2,408:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define isLeapYear(y::integer) => {
#y % 400 == 0 ? return true
#y % 100 == 0 ? return false
Line 2,079 ⟶ 2,431:
with f in fridays(2012) do => {^
#f->format('%Q') + '\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 2,096 ⟶ 2,448:
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function lastFriday yyyy
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
convert the long date to dateitems
Line 2,118 ⟶ 2,470:
sort fridays ascending numeric
return fridays
end lastFriday</langsyntaxhighlight>
Example<langsyntaxhighlight LiveCodelang="livecode">put lastFriday("2012")</langsyntaxhighlight>Output<langsyntaxhighlight LiveCodelang="livecode">1 27
2 24
3 30
Line 2,130 ⟶ 2,482:
10 26
11 30
12 28</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">; Determine if a Gregorian calendar year is leap
to leap? :year
output (and
Line 2,177 ⟶ 2,529:
print reduce [(word ?1 "- ?2)] (list :year :month :day)
]
bye</langsyntaxhighlight>
 
{{out}}
Line 2,195 ⟶ 2,547:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
Line 2,214 ⟶ 2,566:
end
 
lastWeekdays("Friday", tonumber(arg[1]))</langsyntaxhighlight>
Command line session:
<pre>>lua lastFridays.lua 2012
Line 2,231 ⟶ 2,583:
 
></pre>
 
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
module lastfriday {
string year
integer y%
input "Year (e.g. 2023):", y%
year=str$(y%,"")
date a="1/1/"+year
date a1="31/12/"+year
double i, b=a, c=a1
for i=b to b+6
if val(date$(i, 1033, "d"))=6 then exit for
next
document result$="Last Friday per month for year " + year + {:
}
for i=i+7 to c step 7
if val(date$(i, 1033, "M")) <>val(date$(i+7, 1033, "M")) then
result$=date$(i, 1033, "M"+chr$(9)+"dd") + {
}
end if
next
report result$
clipboard result$
}
lastfriday
</syntaxhighlight>
 
{{out}}
<pre>
Year (e.g. 2023):2023
Last Friday per month for year 2023:
1 27
2 24
3 31
4 28
5 26
6 30
7 28
8 25
9 29
10 27
11 24
12 29
 
</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">fridays := proc(year)
local i, dt, change, last_days;
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
Line 2,250 ⟶ 2,650:
end proc;
 
fridays(2012);</langsyntaxhighlight>
{{Out|Output}}
<pre>2012-1-27
Line 2,265 ⟶ 2,665:
2012-12-28</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">FridaysOfYear[Y_] :=
NestWhile[(DaysPlus[#, - 1]) &, #, (DateString[#, "DayName"] != "Friday") &] & /@
Most@Reverse@NestList [DaysPlus[# /. {x_, y_, X_} -> {x, y, 1}, - 1] &, {Y + 1, 1, 1}, 12]
Column@FridaysOfYear[2012]</langsyntaxhighlight>
{{out}}
<pre>{2012,1,27}
Line 2,286 ⟶ 2,686:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab"> function t = last_fridays_of_year(y)
t1 = datenum([y,1,1,0,0,0]);
t2 = datenum([y,12,31,0,0,0]);
Line 2,295 ⟶ 2,695:
 
datestr(last_fridays_of_year(2012),'yyyy-mm-dd')
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,313 ⟶ 2,713:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">weekday(year, month, day) := block([m: month, y: year, k],
if m < 3 then (m: m + 12, y: y - 1),
k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4)
Line 2,332 ⟶ 2,732:
lastfridays(2012);
["2012-1-27", "2012-2-24", "2012-3-30", "2012-4-27", "2012-5-25", "2012-6-29",
"2012-7-27","2012-8-31", "2012-9-28", "2012-10-26", "2012-11-30", "2012-12-28"]</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.Util
// a function to check if a year is a leap year
Line 2,385 ⟶ 2,785:
print form(friday.getMonth()) + "-"
println form(friday.getDay())
end</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 2,391 ⟶ 2,791:
{{trans|C}}
Implements the algorithms from both the [[#Java|Java]] and [[#C|C]] implementations.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,467 ⟶ 2,867:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,502 ⟶ 2,902:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times, os, strutils, times
 
const
var timeinfo = getLocalTime getTime()
DaysInMonth: array[Month, int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
timeinfo.year = paramStr(1).parseInt
DayDiffs: array[WeekDay, int] = [3, 4, 5, 6, 0, 1, 2]
for month in mJan .. mDec:
 
timeinfo.month = month
let year = paramStr(1).parseInt
for day in countdown(31, 1):
 
timeinfo.monthday = day
for month in mJan..mDec:
let t = getLocalTime(timeInfoToTime timeinfo)
var lastDay = DaysInMonth[month]
if t.month == month and t.weekday == dFri:
if month == mFeb and year.isLeapYear: lastDay = 29
echo t.format "yyyy-MM-dd"
var date = initDateTime(lastDay, month, year, 0, 0, 0)
break</lang>
date = date - days(DayDiffs[date.weekday])
Sample usage:
echo date.format("yyyy-MM-dd")</syntaxhighlight>
<pre>./lastfriday 2012
 
{{out}}
Sample usage: ./lastfridays 2012
<pre>
2012-01-27
2012-02-24
Line 2,533 ⟶ 2,937:
Using the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html Unix] from the standard OCaml library:
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma"
open Unix
 
Line 2,568 ⟶ 2,972:
done;
done;
Array.iter print_date fridays</langsyntaxhighlight>
 
{{out}}
Line 2,588 ⟶ 2,992:
{{libheader|OCaml Calendar Library}}
 
<langsyntaxhighlight lang="ocaml">open CalendarLib
 
let usage() =
Line 2,612 ⟶ 3,016:
aux num_days
done;
List.iter print_date (List.rev !fridays)</langsyntaxhighlight>
 
Run this script with the command:
Line 2,620 ⟶ 3,024:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: date
 
: lastFridays(y)
Line 2,628 ⟶ 3,032:
while(dup dayOfWeek Date.FRIDAY <>) [ addDays(-1) ]
println
] ;</langsyntaxhighlight>
 
{{out}}
Line 2,648 ⟶ 3,052:
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">\\ Normalized Julian Day Number from date
njd(D) =
{
Line 2,674 ⟶ 3,078:
}
 
for (m=1, 12, a=njd([2012,m+1,0]); print(njdate(a-(a+1)%7)))</langsyntaxhighlight>
 
Output:<pre>
Line 2,689 ⟶ 3,093:
[2012, 11, 30]
[2012, 12, 28]</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Using Free Pascal's DateUtils library would dramatically simplify the coding (see the Delphi example) but for older Pascal implementations the needed routines are the programmer's responsibility.
<syntaxhighlight lang="pascal">
program LastFriday;
 
{$mode objfpc}{$H+}
 
uses
SysUtils;
 
type
weekdays = (Sun,Mon,Tue,Wed,Thu,Fri,Sat);
 
var
m, d, y : integer;
 
function IsLeapYear(Year : integer) : boolean;
begin
if Year mod 4 <> 0 { quick exit in most likely case }
then IsLeapYear := false
else if Year mod 400 = 0
then IsLeapYear := true
else if Year mod 100 = 0
then IsLeapYear := false
else { non-century year and divisible by 4 }
IsLeapYear := true;
end;
 
 
function DaysInMonth(Month, Year : integer) : integer;
const
LastDay : array[1..12] of integer =
(31,28,31,30,31,30,31,31,30,31,30,31);
begin
if (Month = 2) and (IsLeapYear(Year)) then
DaysInMonth := 29
else
DaysInMonth := LastDay[Month];
end;
 
{ return day of week (Sun = 0, Mon = 1, etc.) for a }
{ given mo, da, and yr using Zeller's congruence }
function DayOfWeek(mo, da, yr : integer) : weekdays;
var
y, c, z : integer;
begin
if mo < 3 then
begin
mo := mo + 10;
yr := yr - 1
end
else mo := mo - 2;
y := yr mod 100;
c := yr div 100;
z := (26 * mo - 2) div 10;
z := z + da + y + (y div 4) + (c div 4) - 2 * c + 777;
DayOfWeek := weekdays(z mod 7);
end;
 
{ return the calendar day of the last occurrence of the }
{ specified weekday in the given month and year }
function LastWeekday(k : weekdays; m, y : integer) : integer;
var
d : integer;
w : weekdays;
begin
{ determine weekday for the last day of the month }
d := DaysInMonth(m, y);
w := DayOfWeek(m, d, y);
{ back up as needed to desired weekday }
if w >= k then
LastWeekday := d - (ord(w) - ord(k))
else
LastWeekday := d - (7 - ord(k)) - ord(w);
end;
 
 
begin { main program }
write('Find last Fridays in what year? ');
readln(y);
writeln;
writeln('Month Last Fri');
for m := 1 to 12 do
begin
d := LastWeekday(Fri, m, y);
writeln(m:5,' ',d:5);
end;
end.
</syntaxhighlight>
{{out}}
<pre>
Find last Fridays in what year? 2020
Month Last Fri
1 31
2 28
3 27
4 24
5 29
6 26
7 31
8 28
9 25
10 30
11 27
12 25
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
use DateTime ;
Line 2,702 ⟶ 3,214:
}
say $dt->ymd ;
}</langsyntaxhighlight>
{{out}}
<pre>2012-01-27
Line 2,719 ⟶ 3,231:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
Requires 0.8.1+ (day_of_week() is now ISO 8601 compliant, plus this now uses a new routine: day_of_week()).
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>procedure last_day_of_month(integer y, dow)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dow</span><span style="color: #0000FF;">)</span>
for m=1 to 12 do
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">12</span> <span style="color: #008080;">do</span>
integer d = days_in_month(y,m),
<span style="color: #004080;">integer</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">days_in_month</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">),</span>
a = dow-day_of_week(y,m,d)
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dow</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">day_of_week</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
printf(1,"%4d-%02d-%02d\n",{y,m,d+a-7*(a>0)})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4d-%02d-%02d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">a</span><span style="color: #0000FF;">-</span><span style="color: #000000;">7</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span><span style="color: #0000FF;">)})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
constant FRIDAY=5
<span style="color: #008080;">constant</span> <span style="color: #000000;">FRIDAY</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span>
last_day_of_month(prompt_number("Year:",{1752,9999}),FRIDAY)</lang>
<span style="color: #000080;font-style:italic;">--prompt_number() is not compatible with pwa/p2js
--last_day_of_month(prompt_number("Year:",{1752,9999}),FRIDAY)</span>
<span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2012</span><span style="color: #0000FF;">,</span><span style="color: #000000;">FRIDAY</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Year:2012
2012-01-27
2012-02-24
Line 2,749 ⟶ 3,264:
PHP is generally used for web apps, so I am not implementing the command-line component of this task.
 
<langsyntaxhighlight PHPlang="php"><?php
function last_friday_of_month($year, $month) {
$day = 0;
Line 2,770 ⟶ 3,285:
$year = 2012;
print_last_fridays_of_month($year);
?></langsyntaxhighlight>
 
{{out}}
Line 2,787 ⟶ 3,302:
2012-12-28
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">% for command line argument
main(ARGV) =>
if ARGV.length > 0 then
Year = ARGV[1].to_integer(),
show_year(Year),
nl
end.
 
% Without command line argument
main => go.
 
go =>
show_year(2022),
nl.
 
% Show the months
show_year(Year) =>
foreach(Date in get_months(Year))
println(format_date(Date))
end,
nl.
 
% Format date to YYYY-DD-MM
format_date(Date) = to_fstring("%4d-%02d-%02d",Date[1],Date[2],Date[3]).
 
 
% Return the last Fridays of each month for year Year
get_months(Year) =
[ [ [Year,Month,Day] : Day in 1..max_days_in_month(Year,Month),
dow(Year, Month, Day) == 5].last() : Month in 1..12].
 
 
% Day of week, Sakamoto's method
dow(Y, M, D) = R =>
T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
if M < 3 then
Y := Y - 1
end,
R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.
 
% Maximum days in month
max_days_in_month(Year,Month) = Days =>
if member(Month, [1,3,5,7,8,10,12]) then
Days = 31
elseif member(Month,[4,6,9,11]) then
Days = 30
else
if leap_year(Year) then
Days = 29
else
Days = 28
end
end.
 
% Is Year a leap year?
leap_year(Year) =>
(Year mod 4 == 0, Year mod 100 != 0)
;
Year mod 400 == 0. </syntaxhighlight>
 
===Running the program===
There are several ways to run this program; let's call it "last_friday_of_each_month.pi":
 
===From Picat's shell===
<pre>$ picat
Picat> cl(last_friday_of_each_month)
Picat> show_year(2022)
2022-01-28
2022-02-25
2022-03-25
2022-04-29
2022-05-27
2022-06-24
2022-07-29
2022-08-26
2022-09-30
2022-10-28
2022-11-25
2022-12-30</pre>
 
===From the command line, year as parameter===
Via <code>main(ARGV)</code>.
<pre>$ picat last_friday_of_each_month.pi 2022</pre>
 
===From the command line, as a goal===
<pre>$ picat -g "show_year(2022)" last_friday_of_each_month.pi</pre>
 
===Run the default goal (go/0))===
<pre>$ picat last_friday_of_each_month.pi</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de lastFridays (Y)
(for M 12
(prinl
Line 2,795 ⟶ 3,401:
(find '((D) (= "Friday" (day D)))
(mapcar '((D) (date Y M D)) `(range 31 22)) )
"-" ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (lastFridays 2012)
2012-01-27
2012-02-24
Line 2,809 ⟶ 3,415:
2012-10-26
2012-11-30
2012-12-28</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">int(0..1) last_friday(object day)
{
return day->week_day() == 5 &&
Line 2,823 ⟶ 3,429:
write("%{%s\n%}", days->format_ymd());
return 0;
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
Fridays: procedure (year) options (main); /* 8 January 2013 */
declare year character (4) varying;
Line 2,849 ⟶ 3,455:
end;
end Fridays;
</syntaxhighlight>
</lang>
The command: FRIDAYS /2008 produces:
<pre>
Line 2,884 ⟶ 3,490:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function last-dayofweek {
param(
Line 2,898 ⟶ 3,504:
}
last-dayofweek 2012 "Friday"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,918 ⟶ 3,524:
This script finds the first and/or last or all dates of any of the days of week; accepts <code>[Int32]</code> and <code>[DateTime]</code> values for Month and Year parameters; outputs <code>[DateTime]</code> objects by default but has an option to output time strings in various formats. This script also allows for pipeline input based mainly upon the Month parameter.
This script has a syntax as complex as any PowerShell Cmdlet because it attempts to do everything.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Date0fDayOfWeek
{
Line 3,016 ⟶ 3,622:
}
}
</syntaxhighlight>
</lang>
The default is to return <code>[DateTime]</code> objects:
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,037 ⟶ 3,643:
</pre>
Return the <code>[DateTime]</code> objects as strings (using the default string format):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday -AsString
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,056 ⟶ 3,662:
</pre>
Return the <code>[DateTime]</code> objects as strings (specifying the string format):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday -AsString -Format yyyy-MM-dd
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,076 ⟶ 3,682:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure LastFridayOfEachMonth(yyyy.i,List lfem.i())
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
NewList d.i()
Line 3,109 ⟶ 3,715:
EndIf
Print("...End")
Input()</langsyntaxhighlight>
{{out}}
<pre>Input Year [ 1971 < y < 2038 ]: 2017
Line 3,128 ⟶ 3,734:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import calendar
 
def last_fridays(year):
Line 3,134 ⟶ 3,740:
last_friday = max(week[calendar.FRIDAY]
for week in calendar.monthcalendar(year, month))
print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))</langsyntaxhighlight>
 
{{out}}
Line 3,151 ⟶ 3,757:
2012-12-28</pre>
Another solution
<langsyntaxhighlight lang="python">import calendar
c=calendar.Calendar()
fridays={}
Line 3,165 ⟶ 3,771:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</langsyntaxhighlight>
 
Using reduce
 
<langsyntaxhighlight lang="python">import calendar
c=calendar.Calendar()
fridays={}
Line 3,182 ⟶ 3,788:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</langsyntaxhighlight>
 
using itertools
 
<langsyntaxhighlight lang="python">import calendar
from itertools import chain
f=chain.from_iterable
Line 3,202 ⟶ 3,808:
for item in sorted((month+"-"+day for month,day in fridays.items()),
key=lambda x:int(x.split("-")[1])):
print item</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ over 3 < if [ 1 - ]
dup 4 / over +
over 100 / -
swap 400 / +
swap 1 -
[ table
0 3 2 5 0 3
5 1 4 6 2 4 ]
+ + 7 mod ] is dayofweek ( day month year --> weekday )
 
[ dup 400 mod 0 = iff
[ drop true ] done
dup 100 mod 0 = iff
[ drop false ] done
4 mod 0 = ] is leap ( year --> b )
 
[ swap 1 -
[ table
31 [ dup leap 28 + ]
31 30 31 30 31 31 30
31 30 31 ]
do nip ] is monthdays ( month year --> n )
 
[ number$
2 times
[ char - join
over 10 < if
[ char 0 join ]
swap number$ join ]
echo$ ] is echoymd ( day month year --> )
 
[ dip
[ 2dup monthdays
dup temp put
unrot dayofweek ]
- dup 0 < if [ 7 + ]
temp take swap - ] is lastwkday ( month year wkd --> n )
 
[ temp put
12 times
[ i^ 1+ over
2dup temp share lastwkday
unrot echoymd cr ]
drop temp release ] is lastwkdays ( year wkd --> )
 
[ 5 lastwkdays ] is lastfridays ( year --> )
 
2012 lastfridays</syntaxhighlight>
 
{{out}}
 
<pre>2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">year = commandArgs(T)
d = as.Date(paste0(year, "-01-01"))
fridays = d + seq(by = 7,
Line 3,211 ⟶ 3,883:
364 + (months(d + 30 + 29) == "February"))
message(paste(collapse = "\n", fridays[tapply(
seq_along(fridays), as.POSIXlt(fridays)$mon, max)]))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require srfi/19 math)
Line 3,256 ⟶ 3,928:
(for ([d (last-fridays 2012)])
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,275 ⟶ 3,947:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub MAIN (Int $year = Date.today.year) {
my @fri;
for Date.new("$year-01-01") .. Date.new("$year-12-31") {
Line 3,281 ⟶ 3,953:
}
.say for @fri[1..12];
}</langsyntaxhighlight>
 
Example:
Line 3,300 ⟶ 3,972:
A solution without a result array to store things in:
 
<syntaxhighlight lang="raku" perl6line>sub MAIN (Int $year = Date.today.year) {
say ~.value.reverse.first: *.day-of-week == 5
for classify *.month, Date.new("$year-01-01") .. Date.new("$year-12-31");
}</langsyntaxhighlight>
 
Here, <code>classify</code> sorts the dates into one bin per month (but preserves the order in each bin). We then take the list inside each bin (<code>.value</code>) and find the last (<code>.reverse.first</code>) date which is a Friday.
Line 3,309 ⟶ 3,981:
Another variation where the data flow can be read left to right using feed operators:
 
<syntaxhighlight lang="raku" perl6line>sub MAIN (Int $year = Date.today.year) {
.say for Date.new("$year-01-01") .. Date.new("$year-12-31") ==> classify *.month ==>
map *.value.reverse.first: *.day-of-week == 5
}</langsyntaxhighlight>
 
=={{header|REBOL}}==
The longer version:
<langsyntaxhighlight REBOLlang="rebol">leap-year?: function [year] [to-logic attempt [to-date reduce [29 2 year]]]
 
days-in-feb: function [year] [either leap-year? year [29] [28]]
Line 3,338 ⟶ 4,010:
year: to-integer input
repeat month 12 [print last-friday-of-month month year]
</syntaxhighlight>
</lang>
{{out}}
<pre>rebol last-fridays.reb <<< 2012
Line 3,355 ⟶ 4,027:
</pre>
A shorter version:
<langsyntaxhighlight REBOLlang="rebol">last-fridays-of-year: function [year] [
collect [
repeat month 12 [
Line 3,367 ⟶ 4,039:
 
foreach friday last-fridays-of-year to-integer input [print friday]
</syntaxhighlight>
</lang>
NB. See "Find the last Sunday of each month" Rosetta for alternative (even more succinct) solution
 
Line 3,400 ⟶ 4,072:
║ last day─of─week is then obtained straightforwardly, or via subtraction. ║
╚════════════════════════════════════════════════════════════════════════════════════════════════╝
<langsyntaxhighlight lang="rexx">/*REXX program displays the dates of the last Fridays of each month for any given year.*/
parse arg yyyy /*obtain optional argument from the CL.*/
do j=1 for 12 /*traipse through all the year's months*/
Line 3,449 ⟶ 4,121:
.er: arg ,_; say; say '***error*** (in LASTDOW)'; say /*tell error, and */
say word('day-of-week month year excess', arg(2)) arg(1) a._ /*plug in a choice.*/
say; exit 13 /*··· then exit. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the following input of: &nbsp; &nbsp; <tt> 2012 </tt> &nbsp; &nbsp; or &nbsp; &nbsp; <tt> 12 </tt>}}
<pre>
Friday 27 Jan 2012
Line 3,467 ⟶ 4,139:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "What year to calculate (yyyy) : "
give year
Line 3,489 ⟶ 4,161:
next
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,506 ⟶ 4,178:
2012-11-30
2012-12-28
</pre>
 
=={{header|RPL}}==
With the release of the HP-48, RPL gained some basic functions for calculating the date, but nothing for directly obtaining the day of the week.
{{works with|HP|48}}
≪ { "MON" TUE" "WED" "THU" "FRI" "SAT" "SUN" }
SWAP 0 TSTR 1 3 SUB POS
≫ '<span style="color:blue">WKDAY</span>' STO <span style="color:grey">@ ( dd.mmyyyy → 1..7 )</span>
≪ → year
≪ { }
.02 .13 '''FOR''' month
1 month .13 == DUP .01 month IFTE SWAP year + 1000000 / + +
DUP <span style="color:blue">WKDAY</span> 1 + 7 MOD 1 + NEG DATE+ 2 TRNC +
0.01 '''STEP''' 2 FIX
≫ ≫ '<span style="color:blue">TGIF</span>' STO
 
2012 <span style="color:blue">TGIF</span>
{{out}}
<pre>
1: {27.01 24.02 30.03 27.04 25.05 29.06 27.07 31.08 28.09 26.10 30.11 28.12 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'date'
 
def last_friday(year, month)
Line 3,518 ⟶ 4,211:
 
year = Integer(ARGV.shift)
(1..12).each {|month| puts last_friday(year, month)}</langsyntaxhighlight>
 
Friday is <code>d.wday == 5</code>; the expression <code>(d.wday - 5) % 7</code> counts days after Friday.
Line 3,538 ⟶ 4,231:
 
Or get the last day of the month and go to the previous day until it's a Friday.
<langsyntaxhighlight lang="ruby">require 'date'
 
def last_friday(year, month)
Line 3,545 ⟶ 4,238:
d
end
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">input "Year:";yr
dayOne$ = "01-01-";yr
n1 = date$(dayOne$)
Line 3,562 ⟶ 4,255:
wend
print date$(n1) ' print last Friday's date
next i</langsyntaxhighlight>
<pre>Year:?2013
01/25/2013
Line 3,578 ⟶ 4,271:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::env::args;
use time::{Date, Duration};
 
Line 3,591 ⟶ 4,284:
println!("{}", date - days_back);
});
}</langsyntaxhighlight>
 
{{out}}
Line 3,610 ⟶ 4,303:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import java.util.Calendar
import java.text.SimpleDateFormat
 
Line 3,633 ⟶ 4,326:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>2012-Jan-27
Line 3,653 ⟶ 4,346:
Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Find_last_sunday_of_each_month#Seed7]].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
Line 3,682 ⟶ 4,375:
end for;
end if;
end func;</langsyntaxhighlight>
 
{{out}} when called with <tt>s7 rosetta/lastWeekdayInMonth 5 2013</tt>:
Line 3,701 ⟶ 4,394:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
ask "What year?"
put it into year
Line 3,719 ⟶ 4,412:
add a month to lastDayOfMonth -- advance to last day of next month
end repeat
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,739 ⟶ 4,432:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('DateTime')
var (year=2016) = ARGV.map{.to_i}...
 
Line 3,748 ⟶ 4,441:
}
say dt.ymd
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,768 ⟶ 4,461:
=={{header|Smalltalk}}==
 
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
Pharo Smalltalk
 
Line 3,778 ⟶ 4,471:
thenSelect: [ :each |
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,786 ⟶ 4,479:
 
=={{header|SQL}}==
<syntaxhighlight lang="sql">
<lang SQL>
select to_char( next_day( last_day( add_months( to_date(
:yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday
from dual
connect by level <= 12;
</syntaxhighlight>
</lang>
<pre>
LASTFRIDAY
Line 3,812 ⟶ 4,505:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">program last_fridays
args year
clear
Line 3,838 ⟶ 4,531:
| 30nov2012 |
| 28dec2012 |
+-----------+</langsyntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
import Foundation
 
Line 3,890 ⟶ 4,583:
 
print(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))
</syntaxhighlight>
</lang>
<pre>
1/27/12
Line 3,907 ⟶ 4,600:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
set year [lindex $argv 0]
foreach dm {02/1 03/1 04/1 05/1 06/1 07/1 08/1 09/1 10/1 11/1 12/1 12/32} {
Line 3,914 ⟶ 4,607:
# Print the interesting part
puts [clock format $t -format "%Y-%m-%d" -gmt 1]
}</langsyntaxhighlight>
Sample execution:
<pre>
Line 3,933 ⟶ 4,626:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
year=2012
Line 3,945 ⟶ 4,638:
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 3,964 ⟶ 4,657:
=={{header|UNIX Shell}}==
Using <code>ncal</code>. Will switch to Julian calender as ncal sees fit, and will not calculate past year 9999 (chances are you'll be too dead by then to worry about weekends anyway).
<langsyntaxhighlight lang="bash">#!/bin/sh
 
if [ -z $1 ]; then exit 1; fi
Line 3,972 ⟶ 4,665:
for m in 01 02 03 04 05 06 07 08 09 10 11 12; do
echo $1-$m-`ncal $m $1 | grep Fr | sed 's/.* \([0-9]\)/\1/'`
done</langsyntaxhighlight>
 
 
For systems without ncal:
<langsyntaxhighlight lang="sh">#!/bin/sh
 
# usage: last_fridays [ year]
Line 3,992 ⟶ 4,685:
# Strip leading zeros to avoid octal interpretation
month=$(( 1 + ${month#0} ))
done</langsyntaxhighlight>
 
 
Using <code>date --date</code> from GNU date??? This code is not portable.
 
<langsyntaxhighlight lang="bash">#!/bin/sh
 
# Free code, no limit work
Line 4,066 ⟶ 4,759:
 
# main
last_fridays ${1:-2012}</langsyntaxhighlight>
 
Sample execution:
Line 4,086 ⟶ 4,779:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
*!* OOP implementaion
LOCAL lnYear As Integer, oCalc As fricalc
Line 4,121 ⟶ 4,814:
 
ENDDEFINE
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import time
import os
 
fn main() {
mut year := 0
mut t := time.now()
year = os.input("Please select a year: ").int()
println("Last Fridays of each month of $year")
println("==================================")
for i in 1..13 {
mut j := time.month_days[i-1]
if i == 2 {
if time.is_leap_year(year) {j = 29}
}
for {
t = time.parse('$year-${i:02}-$j 12:30:00')!
if t.weekday_str() == 'Fri' {
println("${time.long_months[i-1]}: $j")
break
}
j--
}
}
}</syntaxhighlight>
{{out}}
<pre>Please select a year: 2012
Last Fridays of each month of 2012
==================================
January: 27
February: 24
March: 30
April: 27
May: 25
June: 29
July: 27
August: 31
September: 28
October: 26
November: 30
December: 28
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-date}}
<syntaxhighlight lang="wren">import "os" for Process
import "./date" for Date
 
var args = Process.arguments
if (args.count != 1) {
Fiber.abort("Please pass just the year to be processed.")
}
 
var year = Num.fromString(args[0])
System.print("The dates of the last Fridays in the month for %(year) are:")
Date.default = Date.isoDate
for (m in 1..12) {
var d = Date.monthLength(year, m)
var dt = Date.new(year, m, d)
var wd = dt.dayOfWeek
if (wd == 5) {
System.print(dt)
} else if (wd > 5) {
System.print(dt.addDays(-wd + 5))
} else {
System.print(dt.addDays(-wd - 2))
}
}</syntaxhighlight>
 
{{out}}
<pre>
$ wren last_friday.wren 2012
The dates of the last Fridays in the month for 2012 are:
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
 
$ wren last_friday.wren 2020
The dates of the last Fridays in the month for 2020 are:
2020-01-31
2020-02-28
2020-03-27
2020-04-24
2020-05-29
2020-06-26
2020-07-31
2020-08-28
2020-09-25
2020-10-30
2020-11-27
2020-12-25
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat)
Line 4,146 ⟶ 4,941:
IntOut(0, LastDay); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 4,166 ⟶ 4,961:
=={{header|zkl}}==
Gregorian calendar
<langsyntaxhighlight lang="zkl">var [const] D=Time.Date;
fcn lastDay(y,d){
[1..12].pump(List,'wrap(m){ // 12 months, closure for y & d
Line 4,175 ⟶ 4,970:
})
}
lastDay(2012,D.Friday).concat("\n").println();</langsyntaxhighlight>
For each month in year y, count back from the last day in the month
until a Friday is found and print that date.
1,981

edits