Find the last Sunday of each month: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 26: Line 26:
=={{header|11l}}==
=={{header|11l}}==


<lang 11l>F last_sundays(year)
<syntaxhighlight lang="11l">F last_sundays(year)
[String] sundays
[String] sundays
L(month) 1..12
L(month) 1..12
Line 37: Line 37:
R sundays
R sundays


print(last_sundays(2013).join("\n"))</lang>
print(last_sundays(2013).join("\n"))</syntaxhighlight>


{{out}}
{{out}}
Line 57: Line 57:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<lang 360asm>* Last Sunday of each month 31/01/2017
<syntaxhighlight lang="360asm">* Last Sunday of each month 31/01/2017
LASTSUND CSECT
LASTSUND CSECT
USING LASTSUND,R13 base register
USING LASTSUND,R13 base register
Line 135: Line 135:
DW DS D packed (PL8) 15num
DW DS D packed (PL8) 15num
YREGS
YREGS
END LASTSUND</lang>
END LASTSUND</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 154: Line 154:
=={{header|Action!}}==
=={{header|Action!}}==
Day of the week is determined using [https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods Sakamoto method].
Day of the week is determined using [https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods Sakamoto method].
<lang Action!>;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
<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 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 ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
Line 218: Line 218:
PrintB2(last) PutE()
PrintB2(last) PutE()
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_the_last_Sunday_of_each_month.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_the_last_Sunday_of_each_month.png Screenshot from Atari 8-bit computer]
Line 258: Line 258:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{Trans|ALGOL W}}
{{Trans|ALGOL W}}
<lang algol68>BEGIN # find the last Sunday in each month of a year #
<syntaxhighlight lang="algol68">BEGIN # find the last Sunday in each month of a year #
# returns true if year is a leap year, false otherwise #
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
# assumes year is in the Gregorian Calendar #
Line 306: Line 306:
)
)
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 324: Line 324:


=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algol">
<lang ALGOL>
BEGIN
BEGIN


Line 432: Line 432:


END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 453: Line 453:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Uses the Day_of_week and isLeapYear procedures from the day-of-the-week and leap-year tasks - included here for convenience.
Uses the Day_of_week and isLeapYear procedures from the day-of-the-week and leap-year tasks - included here for convenience.
<lang algolw>begin % find the last Sunday in each month of a year %
<syntaxhighlight lang="algolw">begin % find the last Sunday in each month of a year %
% returns true if year is a leap year, false otherwise %
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
% assumes year is in the Gregorian Calendar %
Line 508: Line 508:
for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 529: Line 529:
{{Trans|JavaScript}}
{{Trans|JavaScript}}


<lang AppleScript>-- LAST SUNDAYS OF YEAR ------------------------------------------------------
<syntaxhighlight lang="applescript">-- LAST SUNDAYS OF YEAR ------------------------------------------------------


-- lastSundaysOfYear :: Int -> [Date]
-- lastSundaysOfYear :: Int -> [Date]
Line 714: Line 714:
map(column, item 1 of xss)
map(column, item 1 of xss)
end transpose</lang>
end transpose</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2015-01-25 2016-01-31 2017-01-29 2018-01-28 2019-01-27
<pre>2015-01-25 2016-01-31 2017-01-29 2018-01-28 2019-01-27
Line 735: Line 735:
AppleScript's weekday constants can be coerced either to English text or to the integers 1 (for Sunday) to 7 (Saturday).
AppleScript's weekday constants can be coerced either to English text or to the integers 1 (for Sunday) to 7 (Saturday).


<lang AppleScript>on lastSundayOfEachMonthInYear(y)
<syntaxhighlight lang="applescript">on lastSundayOfEachMonthInYear(y)
-- Initialise an AppleScript date to the first day of some month in the specified year.
-- 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}
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 757: Line 757:
end lastSundayOfEachMonthInYear
end lastSundayOfEachMonthInYear


lastSundayOfEachMonthInYear(2020)</lang>
lastSundayOfEachMonthInYear(2020)</syntaxhighlight>


{{Out}}
{{Out}}
Line 776: Line 776:
The above is hard-coded for Sundays. As with the "Last Friday of each month" task [[https://www.rosettacode.org/wiki/Last_Friday_of_each_month#AppleScript Last Friday of each month]], the handler can be made more flexible with a weekday constant parameter, so that it can be used for any last weekday of the months:
The above is hard-coded for Sundays. As with the "Last Friday of each month" task [[https://www.rosettacode.org/wiki/Last_Friday_of_each_month#AppleScript Last Friday of each month]], the handler can be made more flexible with a weekday constant parameter, so that it can be used for any last weekday of the months:


<lang AppleScript>on lastWeekdayWOfEachMonthInYear(w, y) -- Parameters: (AppleScript weekday constant, AD year number)
<syntaxhighlight lang="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.
-- 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}
tell (current date) to set {firstDayOfNextMonth, its day, its year} to {it, 1, y}
Line 800: Line 800:
end lastWeekdayWOfEachMonthInYear
end lastWeekdayWOfEachMonthInYear


lastWeekdayWOfEachMonthInYear(Sunday, 2020)</lang>
lastWeekdayWOfEachMonthInYear(Sunday, 2020)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"./last_Sundays 2020
<pre>"./last_Sundays 2020
Line 818: Line 818:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>lastSundayForMonth: function [m,y][
<syntaxhighlight lang="rebol">lastSundayForMonth: function [m,y][
ensure -> in? m 1..12
ensure -> in? m 1..12


Line 834: Line 834:
]
]


getLastSundays 2013</lang>
getLastSundays 2013</syntaxhighlight>


{{out}}
{{out}}
Line 852: Line 852:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>InputBox, Year, , Enter a year., , 300, 135
<syntaxhighlight lang="autohotkey">InputBox, Year, , Enter a year., , 300, 135
Date := Year . "0101"
Date := Year . "0101"


Line 871: Line 871:


Gui, Show
Gui, Show
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>Last Sundays of 2013:
<pre>Last Sundays of 2013:
Line 889: Line 889:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year]
# syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year]
BEGIN {
BEGIN {
Line 907: Line 907:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 926: Line 926:
=={{header|Batch File}}==
=={{header|Batch File}}==
Uses day of week, last day of month and leapyear routines
Uses day of week, last day of month and leapyear routines
<syntaxhighlight lang="batch file">
<lang Batch File>
@echo off
@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
Line 962: Line 962:
set /a "%2=^!(%1%%4)+(^!^!(%1%%100)-^!^!(%1%%400))"
set /a "%2=^!(%1%%4)+(^!^!(%1%%100)-^!^!(%1%%400))"
exit /b
exit /b
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Line 983: Line 983:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic>
<syntaxhighlight lang="bbcbasic">
INSTALL @lib$+"DATELIB"
INSTALL @lib$+"DATELIB"


Line 993: Line 993:
NEXT
NEXT
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,015: Line 1,015:
=={{header|Befunge}}==
=={{header|Befunge}}==
This is essentially identical to [[Last_Friday_of_each_month#Befunge|Last Friday of each month]] except for the initial day offset.
This is essentially identical to [[Last_Friday_of_each_month#Befunge|Last Friday of each month]] except for the initial day offset.
<lang befunge>":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v
<syntaxhighlight lang="befunge">":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v
v2++6**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5<
v2++6**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5<
>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v
>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v
^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6
^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6
>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8
>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8
^<# #"#"##"#"##!` +76:+1g00,+55,+*<</lang>
^<# #"#"##"#"##!` +76:+1g00,+55,+*<</syntaxhighlight>


{{out}}
{{out}}
Line 1,041: Line 1,041:
Identical to [[Last_Friday_of_each_month#C|Last Friday of each month]] except for removal of the offset day in the output.
Identical to [[Last_Friday_of_each_month#C|Last Friday of each month]] except for removal of the offset day in the output.


<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 1,061: Line 1,061:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace LastSundayOfEachMonth
namespace LastSundayOfEachMonth
Line 1,097: Line 1,097:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Year to calculate: 2013
<pre>Year to calculate: 2013
Line 1,115: Line 1,115:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <windows.h>
#include <windows.h>
#include <iostream>
#include <iostream>
Line 1,215: Line 1,215:
}
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,234: Line 1,234:
</pre>
</pre>
Other solution, based on the Boost DateTime library:
Other solution, based on the Boost DateTime library:
<lang C++>#include <iostream>
<syntaxhighlight lang="c++">#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <cstdlib>
#include <cstdlib>
Line 1,256: Line 1,256:
}
}
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>2013-Jan-27
<pre>2013-Jan-27
Line 1,274: Line 1,274:
=={{header|Clojure}}==
=={{header|Clojure}}==


<lang clojure>(ns last-sundays.core
<syntaxhighlight lang="clojure">(ns last-sundays.core
(:require [clj-time.core :as time]
(:require [clj-time.core :as time]
[clj-time.periodic :refer [periodic-seq]]
[clj-time.periodic :refer [periodic-seq]]
Line 1,299: Line 1,299:
(defn -main [& args]
(defn -main [& args]
(println (last-sundays-of-months (Integer. (first args)))))
(println (last-sundays-of-months (Integer. (first args)))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>2013-01-27
<pre>2013-01-27
Line 1,316: Line 1,316:


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. last-sun.
program-id. last-sun.
data division.
data division.
Line 1,365: Line 1,365:
.
.
end program last-sun.
end program last-sun.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,386: Line 1,386:
First, calculate the day of week of the 1st day of next month. Then figure out how many days you have to go back until the last Sunday of the month.
First, calculate the day of week of the 1st day of next month. Then figure out how many days you have to go back until the last Sunday of the month.


<lang lisp>(defun last-sundays (year)
<syntaxhighlight lang="lisp">(defun last-sundays (year)
(loop for month from 1 to 12
(loop for month from 1 to 12
for last-month-p = (= month 12)
for last-month-p = (= month 12)
Line 1,401: Line 1,401:
(format t "~D-~2,'0D-~2,'0D~%" year month date))))
(format t "~D-~2,'0D-~2,'0D~%" year month date))))


(last-sundays 2013)</lang>
(last-sundays 2013)</syntaxhighlight>
{{out}}
{{out}}
<pre>2013-01-27
<pre>2013-01-27
Line 1,417: Line 1,417:


=={{header|D}}==
=={{header|D}}==
<lang d>void lastSundays(in uint year) {
<syntaxhighlight lang="d">void lastSundays(in uint year) {
import std.stdio, std.datetime;
import std.stdio, std.datetime;


Line 1,430: Line 1,430:
void main() {
void main() {
lastSundays(2013);
lastSundays(2013);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>2013-Jan-27
<pre>2013-Jan-27
Line 1,448: Line 1,448:
{{libheader| System.DateUtils}}
{{libheader| System.DateUtils}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Find_the_last_Sunday_of_each_month;
program Find_the_last_Sunday_of_each_month;


Line 1,497: Line 1,497:


readln;
readln;
end.</lang>
end.</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def lastSunday(year) do
def lastSunday(year) do
Enum.map(1..12, fn month ->
Enum.map(1..12, fn month ->
Line 1,514: Line 1,514:
Enum.each(RC.lastSunday(y), fn {year, month, day} ->
Enum.each(RC.lastSunday(y), fn {year, month, day} ->
:io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
:io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,534: Line 1,534:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(require 'calendar)
<syntaxhighlight lang="lisp">(require 'calendar)


(defun last-sunday (year)
(defun last-sunday (year)
Line 1,547: Line 1,547:
(number-sequence 1 12)))
(number-sequence 1 12)))


(last-sunday 2013)</lang>
(last-sunday 2013)</syntaxhighlight>
{{output}}
{{output}}
<pre>2013-01-27
<pre>2013-01-27
Line 1,563: Line 1,563:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(last_sundays).
-module(last_sundays).


Line 1,578: Line 1,578:
{Year, Month, Ldm - Diff}.
{Year, Month, Ldm - Diff}.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,604: Line 1,604:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>lastSundayOfEachMonth
<syntaxhighlight lang="lisp">lastSundayOfEachMonth
=LAMBDA(y,
=LAMBDA(y,
LAMBDA(monthEnd,
LAMBDA(monthEnd,
Line 1,614: Line 1,614:
)
)
)
)
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
The formula in cell B2 defines an array which populates the range '''B2:B13'''.
The formula in cell B2 defines an array which populates the range '''B2:B13'''.
Line 1,684: Line 1,684:
<p>We use a transformation from and to the Julian Day Number, see also PARI/GP or Fortran.</p>
<p>We use a transformation from and to the Julian Day Number, see also PARI/GP or Fortran.</p>
<p>The formulars used here come from [http://calendars.wikia.com/wiki/Julian_day_number] (section "Calculation").</p>
<p>The formulars used here come from [http://calendars.wikia.com/wiki/Julian_day_number] (section "Calculation").</p>
<lang fsharp>let jdn (year, month, day) =
<syntaxhighlight lang="fsharp">let jdn (year, month, day) =
let a = (14 - month) / 12
let a = (14 - month) / 12
let y = year + 4800 - a
let y = year + 4800 - a
Line 1,711: Line 1,711:
|> List.map (fun x -> date_from_jdn (x - (x+1)%7))
|> List.map (fun x -> date_from_jdn (x - (x+1)%7))
|> List.iter (printfn "%A")
|> List.iter (printfn "%A")
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre>RosettaCode 2016
<pre>RosettaCode 2016
Line 1,729: Line 1,729:
=={{header|Factor}}==
=={{header|Factor}}==
This program expects a year passed in via command line argument. In case you are wondering — yes — Factor has a <tt>last-sunday-of-month</tt> word in its calendar vocabulary. This is par for the course when it comes to Factor.
This program expects a year passed in via command line argument. In case you are wondering — yes — Factor has a <tt>last-sunday-of-month</tt> word in its calendar vocabulary. This is par for the course when it comes to Factor.
<lang factor>USING: calendar calendar.format command-line io kernel math math.parser
<syntaxhighlight lang="factor">USING: calendar calendar.format command-line io kernel math math.parser
sequences ;
sequences ;
IN: rosetta-code.last-sunday
IN: rosetta-code.last-sunday
Line 1,739: Line 1,739:
: main ( -- ) parse-year 12 [ process-month ] times drop ;
: main ( -- ) parse-year 12 [ process-month ] times drop ;


MAIN: main</lang>
MAIN: main</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,758: Line 1,758:


=={{header|FBSL}}==
=={{header|FBSL}}==
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE


DIM date AS INTEGER, dayname AS STRING
DIM date AS INTEGER, dayname AS STRING
Line 1,775: Line 1,775:


PAUSE
PAUSE
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>2013-1-27
<pre>2013-1-27
Line 1,798: Line 1,798:
Their routine is not only fast, but flexible, in particular allowing Month + 1 so that DAYNUM(Y,M + 1,0) gives the last day of month M for M = 1 to 12, with no agony over which month has what last day and leap years or not. If W is the day of week desired, all that remains is to use MOD(D - W,7) to determine the offset back to the desired day of the week and make that shift. There is a problem with the MOD function when negative numbers are involved: it may or may not (depending on computer, compiler, language) return a negative result; by adding 7 and taking a MOD again, this variation is suppressed.
Their routine is not only fast, but flexible, in particular allowing Month + 1 so that DAYNUM(Y,M + 1,0) gives the last day of month M for M = 1 to 12, with no agony over which month has what last day and leap years or not. If W is the day of week desired, all that remains is to use MOD(D - W,7) to determine the offset back to the desired day of the week and make that shift. There is a problem with the MOD function when negative numbers are involved: it may or may not (depending on computer, compiler, language) return a negative result; by adding 7 and taking a MOD again, this variation is suppressed.


The source uses the MODULE protocol for convenience in its usage in larger projects (which contain a calculation for Easter, daylight savings changeover dates, solar azimuth and altitude, etc. which have been removed here), but requires only F77 features, except for the annoyance of the MUNYAD function returning a TYPE(DATEBAG) result to get the three parts. This is an example where a palindromic programming protocol would be so much better. One would write <lang Fortran> D = DAYNUM(Y,M,D) !Daynumber from date.
The source uses the MODULE protocol for convenience in its usage in larger projects (which contain a calculation for Easter, daylight savings changeover dates, solar azimuth and altitude, etc. which have been removed here), but requires only F77 features, except for the annoyance of the MUNYAD function returning a TYPE(DATEBAG) result to get the three parts. This is an example where a palindromic programming protocol would be so much better. One would write <syntaxhighlight lang="fortran"> D = DAYNUM(Y,M,D) !Daynumber from date.
DAYNUM(Y,M,D) = D !Date parts from a day number.</lang>
DAYNUM(Y,M,D) = D !Date parts from a day number.</syntaxhighlight>
But alas, only pl/i offers palindromic functions, and only for SUBSTR.
But alas, only pl/i offers palindromic functions, and only for SUBSTR.


<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE DATEGNASH
MODULE DATEGNASH
C Calculate conforming to complex calendarical contortions.
C Calculate conforming to complex calendarical contortions.
Line 2,059: Line 2,059:
GO TO 10
GO TO 10
END
END
</syntaxhighlight>
</lang>
And after all that, results:
And after all that, results:
<pre>
<pre>
Line 2,085: Line 2,085:
=={{header|Free Pascal}}==
=={{header|Free Pascal}}==


<lang pascal>
<syntaxhighlight lang="pascal">
program sundays;
program sundays;


Line 2,122: Line 2,122:
end;
end;
end.
end.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,142: Line 2,142:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang FreeBASIC>' version 23-06-2015
<syntaxhighlight lang="freebasic">' version 23-06-2015
' compile with: fbc -s console
' compile with: fbc -s console


Line 2,226: Line 2,226:


Loop
Loop
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>For what year do you want to find the last Sunday of the month
<pre>For what year do you want to find the last Sunday of the month
Line 2,246: Line 2,246:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>d = parseDate[ARGS@0]
<syntaxhighlight lang="frink">d = parseDate[ARGS@0]
for m = 1 to 12
for m = 1 to 12
{
{
Line 2,252: Line 2,252:
n = d - parseInt[d -> ### u ###] days
n = d - parseInt[d -> ### u ###] days
println[n->###yyyy-MM-dd###]
println[n->###yyyy-MM-dd###]
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,278: Line 2,278:


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sYear As String 'To store the year chosen
Dim sYear As String 'To store the year chosen
Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday
Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday
Line 2,296: Line 2,296:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,318: Line 2,318:
This is different from the Go code for [[Last Friday of each month]]. It uses the fact that time functions in Go correct for dates: if you enter 32nd of october, Go corrects to 1st of November. So that if 29th of February is corrected to 1st of March, chosen year is not a leap year.
This is different from the Go code for [[Last Friday of each month]]. It uses the fact that time functions in Go correct for dates: if you enter 32nd of october, Go corrects to 1st of November. So that if 29th of February is corrected to 1st of March, chosen year is not a leap year.


<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,364: Line 2,364:
}
}
}
}
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 2,386: Line 2,386:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>enum Day {
<syntaxhighlight lang="groovy">enum Day {
Sun, Mon, Tue, Wed, Thu, Fri, Sat
Sun, Mon, Tue, Wed, Thu, Fri, Sat
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
Line 2,401: Line 2,401:
!months[monthStr] ? months + [(monthStr):sunday] : months
!months[monthStr] ? months + [(monthStr):sunday] : months
}.values().sort()
}.values().sort()
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def ymd = { it.format('yyyy-MM-dd') }
<syntaxhighlight lang="groovy">def ymd = { it.format('yyyy-MM-dd') }
def lastSundays = lastWeekDays.curry(Day.Sun)
def lastSundays = lastWeekDays.curry(Day.Sun)
lastSundays(args[0] as int).each { println (ymd(it)) }</lang>
lastSundays(args[0] as int).each { println (ymd(it)) }</syntaxhighlight>


Execution (Cygwin on Windows 7):
Execution (Cygwin on Windows 7):
Line 2,426: Line 2,426:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>import Data.List (find, intercalate, transpose)
<syntaxhighlight lang="haskell">import Data.List (find, intercalate, transpose)
import Data.Maybe (fromJust)
import Data.Maybe (fromJust)
import Data.Time.Calendar
import Data.Time.Calendar
Line 2,466: Line 2,466:
p x =
p x =
let (_, _, day) = toWeekDate x
let (_, _, day) = toWeekDate x
in dayOfWeek == day</lang>
in dayOfWeek == day</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2018-01-28 2019-01-27 2020-01-26 2021-01-31 2022-01-30 2023-01-29
<pre>2018-01-28 2019-01-27 2020-01-26 2021-01-31 2022-01-30 2023-01-29
Line 2,485: Line 2,485:
This is a trivial adaptation of the solution to the "Last Friday of each month" task
This is a trivial adaptation of the solution to the "Last Friday of each month" task
and works in both languages:
and works in both languages:
<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
every write(lastsundays(!A))
every write(lastsundays(!A))
end
end
Line 2,504: Line 2,504:
end
end
link datetime, printf</lang>
link datetime, printf</syntaxhighlight>


Sample run:
Sample run:
Line 2,538: Line 2,538:
=={{header|J}}==
=={{header|J}}==
Same solution as for [[Last_Friday_of_each_month#J]]
Same solution as for [[Last_Friday_of_each_month#J]]
<lang j>require'dates'
<syntaxhighlight lang="j">require'dates'
last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1</lang>
last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1</syntaxhighlight>


Example use:
Example use:
<lang j> last_sundays 2013
<syntaxhighlight lang="j"> last_sundays 2013
2013 1 27
2013 1 27
2013 2 24
2013 2 24
Line 2,554: Line 2,554:
2013 10 27
2013 10 27
2013 11 24
2013 11 24
2013 12 29</lang>
2013 12 29</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.Scanner;
<syntaxhighlight lang="java">import java.util.Scanner;


public class LastSunday
public class LastSunday
Line 2,628: Line 2,628:
s.close();
s.close();
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,649: Line 2,649:
</pre>
</pre>
===Java 8===
===Java 8===
<lang Java>import java.time.*;
<syntaxhighlight lang="java">import java.time.*;
import java.util.stream.*;
import java.util.stream.*;
import static java.time.temporal.TemporalAdjusters.*;
import static java.time.temporal.TemporalAdjusters.*;
Line 2,677: Line 2,677:
}
}


}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
====Iteration====
====Iteration====
<lang javascript>function lastSundayOfEachMonths(year) {
<syntaxhighlight lang="javascript">function lastSundayOfEachMonths(year) {
var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var sundays = [];
var sundays = [];
Line 2,697: Line 2,697:
}
}


console.log(lastSundayOfEachMonths(2013).join('\n'));</lang>
console.log(lastSundayOfEachMonths(2013).join('\n'));</syntaxhighlight>
{{output}}
{{output}}
<pre>2013-01-27
<pre>2013-01-27
Line 2,713: Line 2,713:


====Functional composition====
====Functional composition====
<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 2,785: Line 2,785:
.join('\n');
.join('\n');


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,802: Line 2,802:


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict'
'use strict'


Line 2,907: Line 2,907:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2019-01-27 2020-01-26 2021-01-31 2022-01-30
<pre>2019-01-27 2020-01-26 2021-01-31 2022-01-30
Line 2,925: Line 2,925:
{{works with|jq|1.4}}
{{works with|jq|1.4}}
'''Foundations'''
'''Foundations'''
<lang jq># In case your jq does not have "until" defined:
<syntaxhighlight lang="jq"># In case your jq does not have "until" defined:
def until(cond; next):
def until(cond; next):
def _until:
def _until:
Line 2,950: Line 2,950:
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
else . % 7
else . % 7
end ;</lang>
end ;</syntaxhighlight>
'''findLastSundays'''
'''findLastSundays'''
<lang jq># year and month are numbered conventionally
<syntaxhighlight lang="jq"># year and month are numbered conventionally
def findLastSunday(year; month):
def findLastSunday(year; month):
def isLeapYear:
def isLeapYear:
Line 2,974: Line 2,974:


$year|tonumber|findLastSundays
$year|tonumber|findLastSundays
</syntaxhighlight>
</lang>
'''Example:'''
'''Example:'''
<lang sh>$ jq --arg year 2013 -n -r -f findLastSundays.jq
<syntaxhighlight lang="sh">$ jq --arg year 2013 -n -r -f findLastSundays.jq
YEAR: 2013
YEAR: 2013
January 27
January 27
Line 2,989: Line 2,989:
October 27
October 27
November 24
November 24
December 29</lang>
December 29</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
isdefined(:Date) || using Dates
isdefined(:Date) || using Dates


Line 3,018: Line 3,018:
end
end
end
end
</syntaxhighlight>
</lang>


This code uses the <code>Dates</code> module, which is being incorporated into Julian's standard library with the current development version (<tt>0.4</tt>). I've used <code>isdefined</code> to make this code good for the current stable version (<tt>0.3</tt>) as well as for future releases. If <code>Dates</code> is not installed on your instance of Julian try <code>Pkg.add("Dates")</code> from the <tt>REPL</tt>.
This code uses the <code>Dates</code> module, which is being incorporated into Julian's standard library with the current development version (<tt>0.4</tt>). I've used <code>isdefined</code> to make this code good for the current stable version (<tt>0.3</tt>) as well as for future releases. If <code>Dates</code> is not installed on your instance of Julian try <code>Pkg.add("Dates")</code> from the <tt>REPL</tt>.
Line 3,049: Line 3,049:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
/ List the dates of last Sundays of each month of
/ List the dates of last Sundays of each month of
/ a given year
/ a given year
Line 3,063: Line 3,063:
main: {[y]; lsd1[y];`0: ,"Dates of last Sundays of ",($y); 12 10#arr}
main: {[y]; lsd1[y];`0: ,"Dates of last Sundays of ",($y); 12 10#arr}


</syntaxhighlight>
</lang>
The output of a session with the above script is given below:
The output of a session with the above script is given below:
{{out}}
{{out}}
Line 3,088: Line 3,088:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


import java.util.*
import java.util.*
Line 3,108: Line 3,108:
}
}
}
}
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 3,129: Line 3,129:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
year = integer(web_request -> param('year') || 2013),
year = integer(web_request -> param('year') || 2013),
date = date(#year + '-1-1'),
date = date(#year + '-1-1'),
Line 3,149: Line 3,149:
}
}
}
}
#lastsu -> join('<br />')</lang>
#lastsu -> join('<br />')</syntaxhighlight>
<pre>27 January
<pre>27 January
24 February
24 February
Line 3,165: Line 3,165:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
This program goes a step further and provides a function definition, NthDayOfMonth(), that returns the date of any occurrence of a day in any given month and year. For example: The third Monday in February, the last Monday in May, the fourth Thursday in November, etc.
This program goes a step further and provides a function definition, NthDayOfMonth(), that returns the date of any occurrence of a day in any given month and year. For example: The third Monday in February, the last Monday in May, the fourth Thursday in November, etc.
<syntaxhighlight lang="lb">
<lang lb>
yyyy=2013: if yyyy<1901 or yyyy>2099 then end
yyyy=2013: if yyyy<1901 or yyyy>2099 then end
nda$="Lsu"
nda$="Lsu"
Line 3,246: Line 3,246:
end select
end select
end function
end function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,266: Line 3,266:
=={{header|LiveCode}}==
=={{header|LiveCode}}==
Abstracted version of "last friday of each month". LiveCode dateItem item 7 is day of week. It is numbered 1 (Sunday) to 7 (Saturday).
Abstracted version of "last friday of each month". LiveCode dateItem item 7 is day of week. It is numbered 1 (Sunday) to 7 (Saturday).
<lang LiveCode>function lastDay yyyy, dayofweek
<syntaxhighlight lang="livecode">function lastDay yyyy, dayofweek
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
convert the long date to dateitems
convert the long date to dateitems
Line 3,288: Line 3,288:
sort mydays ascending numeric
sort mydays ascending numeric
return mydays
return mydays
end lastDay</lang>Example<lang LiveCode>put lastDay(2013, 1)</lang>Output<pre>1 27
end lastDay</syntaxhighlight>Example<syntaxhighlight lang="livecode">put lastDay(2013, 1)</syntaxhighlight>Output<pre>1 27
2 24
2 24
3 31
3 31
Line 3,302: Line 3,302:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function isLeapYear (y)
<syntaxhighlight lang="lua">function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
end
Line 3,321: Line 3,321:
end
end


lastWeekdays("Sunday", tonumber(arg[1]))</lang>
lastWeekdays("Sunday", tonumber(arg[1]))</syntaxhighlight>
Command line session:
Command line session:
<pre>>lua lastSundays.lua 2013
<pre>>lua lastSundays.lua 2013
Line 3,340: Line 3,340:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>sundays := proc(year)
<syntaxhighlight lang="maple">sundays := proc(year)
local i, dt, change, last_days;
local i, dt, change, last_days;
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
Line 3,357: Line 3,357:
end proc;
end proc;


sundays(2013);</lang>
sundays(2013);</syntaxhighlight>
{{Out|Output}}
{{Out|Output}}
<pre>
<pre>
Line 3,375: Line 3,375:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang mathematica>LastSundays[year_] :=
<syntaxhighlight lang="mathematica">LastSundays[year_] :=
Table[Last@
Table[Last@
DayRange[{year, i},
DayRange[{year, i},
DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i,
DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i,
12}]
12}]
LastSundays[2013]</lang>
LastSundays[2013]</syntaxhighlight>
{{out}}
{{out}}
<pre>{{2013, 1, 27}, {2013, 2, 24}, {2013, 3, 31}, {2013, 4, 28}, {2013, 5,
<pre>{{2013, 1, 27}, {2013, 2, 24}, {2013, 3, 31}, {2013, 4, 28}, {2013, 5,
Line 3,387: Line 3,387:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import os, strutils, times
<syntaxhighlight lang="nim">import os, strutils, times


const
const
Line 3,400: Line 3,400:
var date = initDateTime(lastDay, month, year, 0, 0, 0)
var date = initDateTime(lastDay, month, year, 0, 0, 0)
date = date - days(DayDiffs[date.weekday])
date = date - days(DayDiffs[date.weekday])
echo date.format("yyyy-MM-dd")</lang>
echo date.format("yyyy-MM-dd")</syntaxhighlight>
Sample usage:
Sample usage:
<pre>./lastsunday 2013
<pre>./lastsunday 2013
Line 3,417: Line 3,417:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang OCaml>
let is_leap_year y =
let is_leap_year y =
(* See OCaml solution on Rosetta Code for
(* See OCaml solution on Rosetta Code for
Line 3,459: Line 3,459:
2 -> print_last_sundays( int_of_string (Sys.argv.(1)));
2 -> print_last_sundays( int_of_string (Sys.argv.(1)));
|_ -> invalid_arg "Please enter a year";
|_ -> invalid_arg "Please enter a year";
</syntaxhighlight>
</lang>
Sample usage:
Sample usage:
<pre> ocaml sundays.ml 2013
<pre> ocaml sundays.ml 2013
Line 3,476: Line 3,476:


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>import: date
<syntaxhighlight lang="oforth">import: date


: lastSunday(y)
: lastSunday(y)
Line 3,483: Line 3,483:
Date newDate(y, m, Date.DaysInMonth(y, m))
Date newDate(y, m, Date.DaysInMonth(y, m))
while(dup dayOfWeek Date.SUNDAY <>) [ addDays(-1) ] println
while(dup dayOfWeek Date.SUNDAY <>) [ addDays(-1) ] println
] ;</lang>
] ;</syntaxhighlight>


{{out}}
{{out}}
Line 3,503: Line 3,503:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==


<lang parigp>\\ Normalized Julian Day Number from date
<syntaxhighlight lang="parigp">\\ Normalized Julian Day Number from date
njd(D) =
njd(D) =
{
{
Line 3,527: Line 3,527:
}
}


for (m=1, 12, a=njd([2013,m+1,0]); print(njdate(a-(a+6)%7)))</lang>
for (m=1, 12, a=njd([2013,m+1,0]); print(njdate(a-(a+6)%7)))</syntaxhighlight>


Output:<pre>
Output:<pre>
Line 3,545: Line 3,545:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict ;
use strict ;
use warnings ;
use warnings ;
Line 3,558: Line 3,558:
my $ymd = $date->ymd ;
my $ymd = $date->ymd ;
print "$ymd\n" ;
print "$ymd\n" ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>2013-01-27
<pre>2013-01-27
Line 3,576: Line 3,576:
=={{header|Phix}}==
=={{header|Phix}}==
Requires 0.8.1 (day_of_week() is now ISO 8601 compliant)
Requires 0.8.1 (day_of_week() is now ISO 8601 compliant)
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 3,601: Line 3,601:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2013</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SUNDAY</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">last_day_of_month</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2013</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SUNDAY</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,619: Line 3,619:


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP><?php
<syntaxhighlight lang="php"><?php
// Created with PHP 7.0
// Created with PHP 7.0


Line 3,634: Line 3,634:


printLastSundayOfAllMonth($argv[1]);
printLastSundayOfAllMonth($argv[1]);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,651: Line 3,651:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de lastSundays (Y)
<syntaxhighlight lang="picolisp">(de lastSundays (Y)
(for M 12
(for M 12
(prinl
(prinl
Line 3,657: Line 3,657:
(find '((D) (= "Sunday" (day D)))
(find '((D) (= "Sunday" (day D)))
(mapcar '((D) (date Y M D)) `(range 31 22)) )
(mapcar '((D) (date Y M D)) `(range 31 22)) )
"-" ) ) ) )</lang>
"-" ) ) ) )</syntaxhighlight>
Test:
Test:
<lang PicoLisp>: (lastSundays 2013)
<syntaxhighlight lang="picolisp">: (lastSundays 2013)
2013-01-27
2013-01-27
2013-02-24
2013-02-24
Line 3,671: Line 3,671:
2013-10-27
2013-10-27
2013-11-24
2013-11-24
2013-12-29</lang>
2013-12-29</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function last-dayofweek {
function last-dayofweek {
param(
param(
Line 3,688: Line 3,688:
}
}
last-dayofweek 2013 "Sunday"
last-dayofweek 2013 "Sunday"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 3,708: Line 3,708:
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 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.
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
function Get-Date0fDayOfWeek
{
{
Line 3,806: Line 3,806:
}
}
}
}
</syntaxhighlight>
</lang>
The default is to return <code>[DateTime]</code> objects:
The default is to return <code>[DateTime]</code> objects:
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,827: Line 3,827:
</pre>
</pre>
Return the <code>[DateTime]</code> objects as strings (using the default string format):
Return the <code>[DateTime]</code> objects as strings (using the default string format):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,846: Line 3,846:
</pre>
</pre>
Return the <code>[DateTime]</code> objects as strings (specifying the string format):
Return the <code>[DateTime]</code> objects as strings (specifying the string format):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString -Format yyyy-MM-dd
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString -Format yyyy-MM-dd
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,866: Line 3,866:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure LastSundayOfEachMonth(yyyy.i,List lfem.i())
<syntaxhighlight lang="purebasic">Procedure LastSundayOfEachMonth(yyyy.i,List lfem.i())
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
NewList d.i()
NewList d.i()
Line 3,899: Line 3,899:
EndIf
EndIf
Print("...End")
Print("...End")
Input()</lang>
Input()</syntaxhighlight>
{{out}}
{{out}}
<pre>Input Year [ 1971 < y < 2038 ]: 2013
<pre>Input Year [ 1971 < y < 2038 ]: 2013
Line 3,918: Line 3,918:


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<syntaxhighlight lang="python">
import sys
import sys
import calendar
import calendar
Line 3,932: Line 3,932:
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))
</syntaxhighlight>
</lang>


<b>Output</b>:
<b>Output</b>:
<lang>
<syntaxhighlight lang="text">
2013-Jan-27
2013-Jan-27
2013-Feb-24
2013-Feb-24
Line 3,948: Line 3,948:
2013-Nov-24
2013-Nov-24
2013-Dec-29
2013-Dec-29
</syntaxhighlight>
</lang>


=={{header|QuickBASIC 4.5}}==
=={{header|QuickBASIC 4.5}}==
QuickBASIC 4.5 doesn't have a way to manage dates easily. Following you'll see my solution for this task in QuickBASIC/QBASIC
QuickBASIC 4.5 doesn't have a way to manage dates easily. Following you'll see my solution for this task in QuickBASIC/QBASIC
<syntaxhighlight lang="qbasic">
<lang QBASIC>
' PROGRAM Last Sundays in Quick BASIC 4.5 (LASTSQB1)
' PROGRAM Last Sundays in Quick BASIC 4.5 (LASTSQB1)
' This program will calculate the last Sundays of each month in a given year.
' This program will calculate the last Sundays of each month in a given year.
Line 4,076: Line 4,076:


END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,098: Line 4,098:
==={{header|VB-DOS 1.0}}===
==={{header|VB-DOS 1.0}}===
As VB-DOS uses serial numbers for dates and includes some useful functions to work with dates, it is easier to do this code in VB-DOS.
As VB-DOS uses serial numbers for dates and includes some useful functions to work with dates, it is easier to do this code in VB-DOS.
<syntaxhighlight lang="qbasic">
<lang QBASIC>
OPTION EXPLICIT
OPTION EXPLICIT


Line 4,151: Line 4,151:
LastSundayOfMonth = iLSoM
LastSundayOfMonth = iLSoM
END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,173: Line 4,173:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ over 3 < if [ 1 - ]
<syntaxhighlight lang="quackery"> [ over 3 < if [ 1 - ]
dup 4 / over +
dup 4 / over +
over 100 / -
over 100 / -
Line 4,220: Line 4,220:
[ 0 lastwkdays ] is lastsundays ( year --> )
[ 0 lastwkdays ] is lastsundays ( year --> )


2013 lastsundays</lang>
2013 lastsundays</syntaxhighlight>


{{out}}
{{out}}
Line 4,238: Line 4,238:


=={{header|R}}==
=={{header|R}}==
<lang rsplus>
<syntaxhighlight lang="rsplus">
last_sundays <- function(year) {
last_sundays <- function(year) {
for (month in 1:12) {
for (month in 1:12) {
Line 4,253: Line 4,253:
}
}
last_sundays(2004)
last_sundays(2004)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,271: Line 4,271:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require srfi/19 math)
(require srfi/19 math)
Line 4,313: Line 4,313:
(for ([d (last-sundays 2013)])
(for ([d (last-sundays 2013)])
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,334: Line 4,334:


{{works with|rakudo|2018.03}}
{{works with|rakudo|2018.03}}
<lang perl6>sub MAIN ($year = Date.today.year) {
<syntaxhighlight lang="raku" line>sub MAIN ($year = Date.today.year) {
for 1..12 -> $month {
for 1..12 -> $month {
my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month);
my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month);
say $month-end - $month-end.day-of-week % 7;
say $month-end - $month-end.day-of-week % 7;
}
}
}</lang>
}</syntaxhighlight>


{{out|input=2018}}
{{out|input=2018}}
Line 4,356: Line 4,356:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>#!/usr/bin/env rebol
<syntaxhighlight lang="rebol">#!/usr/bin/env rebol


last-sundays-of-year: function [
last-sundays-of-year: function [
Line 4,372: Line 4,372:


foreach sunday last-sundays-of-year to-integer system/script/args [print sunday]
foreach sunday last-sundays-of-year to-integer system/script/args [print sunday]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>./last-sundays.reb 2013
<pre>./last-sundays.reb 2013
Line 4,394: Line 4,394:
except for the innards of the first '''DO''' loop. <br><br>
except for the innards of the first '''DO''' loop. <br><br>
The &nbsp; '''lastDOW''' &nbsp; subroutine can be used for any day-of-the-week for any month for any year.
The &nbsp; '''lastDOW''' &nbsp; subroutine can be used for any day-of-the-week for any month for any year.
<lang rexx>/*REXX program displays dates of last Sundays of each month for any year*/
<syntaxhighlight lang="rexx">/*REXX program displays dates of last Sundays of each month for any year*/
parse arg yyyy
parse arg yyyy
do j=1 for 12
do j=1 for 12
Line 4,472: Line 4,472:
.er: arg ,_;say; say '***error!*** (in LASTDOW)';say /*tell error, and */
.er: arg ,_;say; say '***error!*** (in LASTDOW)';say /*tell error, and */
say word('day-of-week month year excess',arg(2)) arg(1) a._
say word('day-of-week month year excess',arg(2)) arg(1) a._
say; exit 13 /*... then exit. */</lang>
say; exit 13 /*... then exit. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input &nbsp; (the current year, &nbsp; 2013):}}
{{out|output|text=&nbsp; when using the default input &nbsp; (the current year, &nbsp; 2013):}}
<pre>
<pre>
Line 4,490: Line 4,490:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see "What year to calculate (yyyy) : "
see "What year to calculate (yyyy) : "
give year
give year
Line 4,509: Line 4,509:
next
next
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,529: Line 4,529:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'date'
<syntaxhighlight lang="ruby">require 'date'


def last_sundays_of_year(year = Date.today.year)
def last_sundays_of_year(year = Date.today.year)
Line 4,538: Line 4,538:
end
end


puts last_sundays_of_year(2013)</lang>
puts last_sundays_of_year(2013)</syntaxhighlight>


{{out}}
{{out}}
Line 4,558: Line 4,558:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>input "What year to calculate (yyyy) : ";year
<syntaxhighlight lang="runbasic">input "What year to calculate (yyyy) : ";year
print "Last Sundays in ";year;" are:"
print "Last Sundays in ";year;" are:"
dim month(12)
dim month(12)
Line 4,575: Line 4,575:
if x = 4 then print year ; "-";right$("0"+str$(n),2);"-" ; i
if x = 4 then print year ; "-";right$("0"+str$(n),2);"-" ; i
next
next
next</lang>
next</syntaxhighlight>
<pre>
<pre>
What year to calculate (yyyy) : ?2013
What year to calculate (yyyy) : ?2013
Line 4,593: Line 4,593:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::env::args;
<syntaxhighlight lang="rust">use std::env::args;
use time::{Date, Duration};
use time::{Date, Duration};


Line 4,606: Line 4,606:
println!("{}", date - days_back);
println!("{}", date - days_back);
});
});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,624: Line 4,624:


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
<lang basic>
<syntaxhighlight lang="basic">
rem - return p mod q
rem - return p mod q
function mod(p, q = integer) = integer
function mod(p, q = integer) = integer
Line 4,695: Line 4,695:
print shortmonth(m);" ";lastkday(SUNDAY, m, y)
print shortmonth(m);" ";lastkday(SUNDAY, m, y)
next m
next m
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,713: Line 4,713:


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>object FindTheLastSundayOfEachMonth extends App {
<syntaxhighlight lang="scala">object FindTheLastSundayOfEachMonth extends App {
import java.util.Calendar._
import java.util.Calendar._
val cal = getInstance
val cal = getInstance
Line 4,727: Line 4,727:
val fmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
val fmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
println(lastSundaysOf(year).map(fmt.format) mkString "\n")
println(lastSundaysOf(year).map(fmt.format) mkString "\n")
}</lang>
}</syntaxhighlight>
===Java 8===
===Java 8===
<lang Scala>object FindTheLastSundayOfEachMonth extends App {
<syntaxhighlight lang="scala">object FindTheLastSundayOfEachMonth extends App {
def lastSundaysOf(year: Int) = (1 to 12).map{month =>
def lastSundaysOf(year: Int) = (1 to 12).map{month =>
import java.time._; import java.time.temporal.TemporalAdjusters._
import java.time._; import java.time.temporal.TemporalAdjusters._
Line 4,736: Line 4,736:
val year = args.headOption.map(_.toInt).getOrElse(java.time.LocalDate.now.getYear)
val year = args.headOption.map(_.toInt).getOrElse(java.time.LocalDate.now.getYear)
println(lastSundaysOf(year) mkString "\n")
println(lastSundaysOf(year) mkString "\n")
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 4,743: Line 4,743:
Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Last_Friday_of_each_month#Seed7]].
Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Last_Friday_of_each_month#Seed7]].


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "time.s7i";
include "time.s7i";
include "duration.s7i";
include "duration.s7i";
Line 4,772: Line 4,772:
end for;
end for;
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


{{out}} when called with <tt>s7 rosetta/lastWeekdayInMonth 7 2013</tt>:
{{out}} when called with <tt>s7 rosetta/lastWeekdayInMonth 7 2013</tt>:
Line 4,791: Line 4,791:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var dt = require('DateTime');
<syntaxhighlight lang="ruby">var dt = require('DateTime');
var (year=2016) = ARGV.map{.to_i}...
var (year=2016) = ARGV.map{.to_i}...


Line 4,805: Line 4,805:


say date.ymd;
say date.ymd;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,824: Line 4,824:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
Pharo Smalltalk
Pharo Smalltalk


Line 4,834: Line 4,834:
thenSelect: [ :each |
thenSelect: [ :each |
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,842: Line 4,842:


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>program last_sundays
<syntaxhighlight lang="stata">program last_sundays
args year
args year
clear
clear
Line 4,868: Line 4,868:
| 24nov2013 |
| 24nov2013 |
| 29dec2013 |
| 29dec2013 |
+-----------+</lang>
+-----------+</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


func lastSundays(of year: Int) -> [Date] {
func lastSundays(of year: Int) -> [Date] {
Line 4,901: Line 4,901:
dateFormatter.dateStyle = .short
dateFormatter.dateStyle = .short


print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))</lang>
print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,919: Line 4,919:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc lastSundays {{year ""}} {
<syntaxhighlight lang="tcl">proc lastSundays {{year ""}} {
if {$year eq ""} {
if {$year eq ""} {
set year [clock format [clock seconds] -gmt 1 -format "%Y"]
set year [clock format [clock seconds] -gmt 1 -format "%Y"]
Line 4,932: Line 4,932:
return $result
return $result
}
}
puts [join [lastSundays {*}$argv] "\n"]</lang>
puts [join [lastSundays {*}$argv] "\n"]</syntaxhighlight>
{{out}}
{{out}}
When called as: “<code>tclsh lastSundays.tcl 2013</code>” (or with the year argument omitted during 2013)
When called as: “<code>tclsh lastSundays.tcl 2013</code>” (or with the year argument omitted during 2013)
Line 4,955: Line 4,955:
This uses the programs awk and cal, which are usually installed on any POSIXlike system.
This uses the programs awk and cal, which are usually installed on any POSIXlike system.


<lang sh>last_sundays() {
<syntaxhighlight lang="sh">last_sundays() {
local y=$1
local y=$1
for (( m=1; m<=12; ++m )); do
for (( m=1; m<=12; ++m )); do
cal $m $y | awk -vy=$y -vm=$m '/^.[0-9]/ {d=$1} END {print y"-"m"-"d}'
cal $m $y | awk -vy=$y -vm=$m '/^.[0-9]/ {d=$1} END {print y"-"m"-"d}'
done
done
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 4,979: Line 4,979:
=={{header|VBScript}}==
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
<lang VBScript>
strYear = WScript.StdIn.ReadLine
strYear = WScript.StdIn.ReadLine


Line 4,986: Line 4,986:
WScript.Echo d - Weekday(d) + 1
WScript.Echo d - Weekday(d) + 1
Next
Next
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-date}}
{{libheader|Wren-date}}
<lang ecmascript>import "os" for Process
<syntaxhighlight lang="ecmascript">import "os" for Process
import "/date" for Date
import "/date" for Date
Line 5,010: Line 5,010:
System.print(dt.addDays(-wd))
System.print(dt.addDays(-wd))
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,046: Line 5,046:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat)
<syntaxhighlight lang="xpl0">func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat)
int Year, Month, Day; \works for years from 1583 onward
int Year, Month, Day; \works for years from 1583 onward
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
Line 5,064: Line 5,064:
IntOut(0, LastDay); CrLf(0);
IntOut(0, LastDay); CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}