Find the last Sunday of each month: Difference between revisions
Find the last Sunday of each month (view source)
Revision as of 17:04, 16 December 2023
, 5 months agoAdd Easylang
(Fixed order (Free Pascal, FreeBASIC)) |
(Add Easylang) |
||
(16 intermediate revisions by 8 users not shown) | |||
Line 26:
=={{header|11l}}==
<
[String] sundays
L(month) 1..12
Line 37:
R sundays
print(last_sundays(2013).join("\n"))</
{{out}}
Line 57:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
LASTSUND CSECT
USING LASTSUND,R13 base register
Line 135:
DW DS D packed (PL8) 15num
YREGS
END LASTSUND</
{{out}}
<pre>
Line 154:
=={{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].
<
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]
Line 218:
PrintB2(last) PutE()
OD
RETURN</
{{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]
Line 258:
=={{header|ALGOL 68}}==
{{Trans|ALGOL W}}
<
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
Line 306:
)
OD
END</
{{out}}
<pre>
Line 324:
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algol">
BEGIN
Line 432:
END
</syntaxhighlight>
{{out}}
<pre>
Line 453:
=={{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.
<
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
Line 508:
for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
end
end.</
{{out}}
<pre>
Line 529:
{{Trans|JavaScript}}
<
-- lastSundaysOfYear :: Int -> [Date]
Line 714:
map(column, item 1 of xss)
end transpose</
{{Out}}
<pre>2015-01-25 2016-01-31 2017-01-29 2018-01-28 2019-01-27
Line 735:
AppleScript's weekday constants can be coerced either to English text or to the integers 1 (for Sunday) to 7 (Saturday).
<
-- 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 757:
end lastSundayOfEachMonthInYear
lastSundayOfEachMonthInYear(2020)</
{{Out}}
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:
<
-- 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 800:
end lastWeekdayWOfEachMonthInYear
lastWeekdayWOfEachMonthInYear(Sunday, 2020)</
{{Out}}
<pre>"./last_Sundays 2020
Line 818:
=={{header|Arturo}}==
<
ensure -> in? m 1..12
Line 834:
]
getLastSundays 2013</
{{out}}
Line 852:
=={{header|AutoHotkey}}==
<
Date := Year . "0101"
Line 871:
Gui, Show
return</
{{out}}
<pre>Last Sundays of 2013:
Line 889:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year]
BEGIN {
Line 907:
exit(0)
}
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 926:
=={{header|Batch File}}==
Uses day of week, last day of month and leapyear routines
<syntaxhighlight lang="batch file">
@echo off
setlocal enabledelayedexpansion
Line 962:
set /a "%2=^!(%1%%4)+(^!^!(%1%%100)-^!^!(%1%%400))"
exit /b
</syntaxhighlight>
{{out}}
Line 983:
=={{header|BBC BASIC}}==
<
INSTALL @lib$+"DATELIB"
Line 993:
NEXT
END
</syntaxhighlight>
{{out}}
<pre>
Line 1,015:
=={{header|Befunge}}==
This is essentially identical to [[Last_Friday_of_each_month#Befunge|Last Friday of each month]] except for the initial day offset.
<
v2++6**"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,+*<</
{{out}}
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.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 1,061:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
namespace LastSundayOfEachMonth
Line 1,097:
}
}
</syntaxhighlight>
{{out}}
<pre>Year to calculate: 2013
Line 1,115:
=={{header|C++}}==
<
#include <windows.h>
#include <iostream>
Line 1,215:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
{{out}}
<pre>
Line 1,234:
</pre>
Other solution, based on the Boost DateTime library:
<
#include <boost/date_time/gregorian/gregorian.hpp>
#include <cstdlib>
Line 1,256:
}
return 0 ;
}</
{{out}}
<pre>2013-Jan-27
Line 1,270:
2013-Nov-24
2013-Dec-29
</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 Sunday 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::Sunday ) {
ymd = std::chrono::sys_days{ymd} - std::chrono::days{1};
}
std::cout << ymd << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
The dates of the last Sunday in each month of 2023:
2023-01-29
2023-02-26
2023-03-26
2023-04-30
2023-05-28
2023-06-25
2023-07-30
2023-08-27
2023-09-24
2023-10-29
2023-11-26
2023-12-31
</pre>
=={{header|Clojure}}==
<
(:require [clj-time.core :as time]
[clj-time.periodic :refer [periodic-seq]]
Line 1,299 ⟶ 1,340:
(defn -main [& args]
(println (last-sundays-of-months (Integer. (first args)))))
</syntaxhighlight>
{{out}}
<pre>2013-01-27
Line 1,316 ⟶ 1,357:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
program-id. last-sun.
data division.
Line 1,365 ⟶ 1,406:
.
end program last-sun.
</syntaxhighlight>
{{out}}
Line 1,386 ⟶ 1,427:
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.
<
(loop for month from 1 to 12
for last-month-p = (= month 12)
Line 1,401 ⟶ 1,442:
(format t "~D-~2,'0D-~2,'0D~%" year month date))))
(last-sundays 2013)</
{{out}}
<pre>2013-01-27
Line 1,417 ⟶ 1,458:
=={{header|D}}==
<
import std.stdio, std.datetime;
Line 1,430 ⟶ 1,471:
void main() {
lastSundays(2013);
}</
{{out}}
<pre>2013-Jan-27
Line 1,448 ⟶ 1,489:
{{libheader| System.DateUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Find_the_last_Sunday_of_each_month;
Line 1,497 ⟶ 1,538:
readln;
end.</
=={{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_sundays year . .
for m to 12
d = mdays[m]
if m = 2 and leap year = 1
d = 29
.
d -= weekday year m d - 1
m$ = m
if m < 10
m$ = "0" & m
.
print year & "-" & m$ & "-" & d
.
.
last_sundays 2023
</syntaxhighlight>
=={{header|Elixir}}==
<
def lastSunday(year) do
Enum.map(1..12, fn month ->
Line 1,514 ⟶ 1,592:
Enum.each(RC.lastSunday(y), fn {year, month, day} ->
:io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
end)</
{{out}}
Line 1,532 ⟶ 1,610:
2013-12-29
</pre>
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(require 'calendar)
(defun last-sunday (year)
"Print the last Sunday 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))
(lastsunday (1+ (cl-position 0 weekdays :from-end t))))
(insert (format "%i-%02i-%02i \n" year month lastsunday))))
(number-sequence 1 12)))
(last-sunday 2013)</syntaxhighlight>
{{output}}
<pre>2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29 </pre>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(last_sundays).
Line 1,549 ⟶ 1,656:
{Year, Month, Ldm - Diff}.
</syntaxhighlight>
{{out}}
<pre>
Line 1,575 ⟶ 1,682:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(y,
LAMBDA(monthEnd,
Line 1,585 ⟶ 1,692:
)
)
)</
{{Out}}
The formula in cell B2 defines an array which populates the range '''B2:B13'''.
Line 1,655 ⟶ 1,762:
<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>
<
let a = (14 - month) / 12
let y = year + 4800 - a
Line 1,682 ⟶ 1,789:
|> List.map (fun x -> date_from_jdn (x - (x+1)%7))
|> List.iter (printfn "%A")
0</
{{out}}
<pre>RosettaCode 2016
Line 1,700 ⟶ 1,807:
=={{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.
<
sequences ;
IN: rosetta-code.last-sunday
Line 1,710 ⟶ 1,817:
: main ( -- ) parse-year 12 [ process-month ] times drop ;
MAIN: main</
{{out}}
<pre>
Line 1,729 ⟶ 1,836:
=={{header|FBSL}}==
<
DIM date AS INTEGER, dayname AS STRING
Line 1,746 ⟶ 1,853:
PAUSE
</syntaxhighlight>
{{out}}
<pre>2013-1-27
Line 1,769 ⟶ 1,876:
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 <
DAYNUM(Y,M,D) = D !Date parts from a day number.</
But alas, only pl/i offers palindromic functions, and only for SUBSTR.
<syntaxhighlight lang="fortran">
MODULE DATEGNASH
C Calculate conforming to complex calendarical contortions.
Line 2,030 ⟶ 2,137:
GO TO 10
END
</syntaxhighlight>
And after all that, results:
<pre>
Line 2,056 ⟶ 2,163:
=={{header|Free Pascal}}==
<
program sundays;
Line 2,093 ⟶ 2,200:
end;
end.
</syntaxhighlight>
{{out}}
Line 2,113 ⟶ 2,220:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,197 ⟶ 2,304:
Loop
End</
{{out}}
<pre>For what year do you want to find the last Sunday of the month
Line 2,217 ⟶ 2,324:
=={{header|Frink}}==
<
for m = 1 to 12
{
Line 2,223 ⟶ 2,330:
n = d - parseInt[d -> ### u ###] days
println[n->###yyyy-MM-dd###]
}</
{{out}}
Line 2,242 ⟶ 2,349:
=={{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 02.png]]
[[File:Fōrmulæ - Last day of each month of a year, being a given weekday 03.png]]
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
Long y, c, d, i
void local fn sunday( m as Short, nd as Short)
if d > nd then d -= 7 // Don't overshoot
print y @"–"m @"–"d
d = d + 35 - nd // Advance 5 weeks minus month length
end fn
void local fn month( m as Short )
select m
case 1
if ( y mod 4 > 0 ) or ( y mod 100 == 0 and y mod 400 > 0 )
fn sunday( m, 31)
fn sunday( m + 1, 28)
else
d += 1 // Extra day for leap year
fn sunday( m, 31 )
fn sunday( m + 1, 29 )
end if
case 3, 5, 7, 8, 10, 12
fn sunday( m, 31 )
case 4, 6, 9, 11
fn sunday( m, 30 )
end select
end fn
y = 2024
// Concentrate from D. Knuth: CACM 1962;5:209
c = y / 100 + 1
d = ( 3 * c / 4 ) - ( 5 * y / 4 )
d = ( d mod 7 ) + 36 // A Sunday in February
for i = 1 to 12
fn month( i )
next
handleevents
</syntaxhighlight>
Output:
<pre>
2024-1-28
2024-2-25
2024-3-31
2024-4-28
2024-5-26
2024-6-30
2024-7-28
2024-8-25
2024-9-29
2024-10-27
2024-11-24
2024-12-29
</pre>
=={{header|Gambas}}==
<
Dim sYear As String 'To store the year chosen
Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday
Line 2,267 ⟶ 2,438:
Next
End</
Output:
<pre>
Line 2,289 ⟶ 2,460:
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.
<
import (
Line 2,335 ⟶ 2,506:
}
}
</syntaxhighlight>
<pre>
Line 2,357 ⟶ 2,528:
=={{header|Groovy}}==
Solution:
<
Sun, Mon, Tue, Wed, Thu, Fri, Sat
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
Line 2,372 ⟶ 2,543:
!months[monthStr] ? months + [(monthStr):sunday] : months
}.values().sort()
}</
Test:
<
def lastSundays = lastWeekDays.curry(Day.Sun)
lastSundays(args[0] as int).each { println (ymd(it)) }</
Execution (Cygwin on Windows 7):
Line 2,397 ⟶ 2,568:
=={{header|Haskell}}==
<
import Data.Maybe (fromJust)
import Data.Time.Calendar
Line 2,437 ⟶ 2,608:
p x =
let (_, _, day) = toWeekDate x
in dayOfWeek == day</
{{Out}}
<pre>2018-01-28 2019-01-27 2020-01-26 2021-01-31 2022-01-30 2023-01-29
Line 2,456 ⟶ 2,627:
This is a trivial adaptation of the solution to the "Last Friday of each month" task
and works in both languages:
<
every write(lastsundays(!A))
end
Line 2,475 ⟶ 2,646:
end
link datetime, printf</
Sample run:
Line 2,509 ⟶ 2,680:
=={{header|J}}==
Same solution as for [[Last_Friday_of_each_month#J]]
<
last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1</
Example use:
<
2013 1 27
2013 2 24
Line 2,525 ⟶ 2,696:
2013 10 27
2013 11 24
2013 12 29</
=={{header|Java}}==
<
public class LastSunday
Line 2,599 ⟶ 2,770:
s.close();
}
}</
{{out}}
Line 2,620 ⟶ 2,791:
</pre>
===Java 8===
<
import java.util.stream.*;
import static java.time.temporal.TemporalAdjusters.*;
Line 2,648 ⟶ 2,819:
}
}</
=={{header|JavaScript}}==
===ES5===
====Iteration====
<
var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var sundays = [];
Line 2,668 ⟶ 2,839:
}
console.log(lastSundayOfEachMonths(2013).join('\n'));</
{{output}}
<pre>2013-01-27
Line 2,684 ⟶ 2,855:
====Functional composition====
<
'use strict';
Line 2,756 ⟶ 2,927:
.join('\n');
})();</
{{Out}}
Line 2,773 ⟶ 2,944:
===ES6===
<
'use strict'
Line 2,878 ⟶ 3,049:
// MAIN ---
return main();
})();</
{{Out}}
<pre>2019-01-27 2020-01-26 2021-01-31 2022-01-30
Line 2,896 ⟶ 3,067:
{{works with|jq|1.4}}
'''Foundations'''
<
def until(cond; next):
def _until:
Line 2,921 ⟶ 3,092:
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
else . % 7
end ;</
'''findLastSundays'''
<
def findLastSunday(year; month):
def isLeapYear:
Line 2,945 ⟶ 3,116:
$year|tonumber|findLastSundays
</syntaxhighlight>
'''Example:'''
<
YEAR: 2013
January 27
Line 2,960 ⟶ 3,131:
October 27
November 24
December 29</
=={{header|Julia}}==
<syntaxhighlight lang="julia">
isdefined(:Date) || using Dates
Line 2,989 ⟶ 3,160:
end
end
</syntaxhighlight>
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,020 ⟶ 3,191:
=={{header|K}}==
<syntaxhighlight lang="k">
/ List the dates of last Sundays of each month of
/ a given year
Line 3,034 ⟶ 3,205:
main: {[y]; lsd1[y];`0: ,"Dates of last Sundays of ",($y); 12 10#arr}
</syntaxhighlight>
The output of a session with the above script is given below:
{{out}}
Line 3,059 ⟶ 3,230:
=={{header|Kotlin}}==
<
import java.util.*
Line 3,079 ⟶ 3,250:
}
}
}</
Sample input/output:
{{out}}
Line 3,100 ⟶ 3,271:
=={{header|Lasso}}==
<
year = integer(web_request -> param('year') || 2013),
date = date(#year + '-1-1'),
Line 3,120 ⟶ 3,291:
}
}
#lastsu -> join('<br />')</
<pre>27 January
24 February
Line 3,136 ⟶ 3,307:
=={{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.
<syntaxhighlight lang="lb">
yyyy=2013: if yyyy<1901 or yyyy>2099 then end
nda$="Lsu"
Line 3,217 ⟶ 3,388:
end select
end function
</syntaxhighlight>
{{out}}
<pre>
Line 3,237 ⟶ 3,408:
=={{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).
<
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
convert the long date to dateitems
Line 3,259 ⟶ 3,430:
sort mydays ascending numeric
return mydays
end lastDay</
2 24
3 31
Line 3,273 ⟶ 3,444:
=={{header|Lua}}==
<
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
Line 3,292 ⟶ 3,463:
end
lastWeekdays("Sunday", tonumber(arg[1]))</
Command line session:
<pre>>lua lastSundays.lua 2013
Line 3,311 ⟶ 3,482:
=={{header|Maple}}==
<
local i, dt, change, last_days;
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
Line 3,328 ⟶ 3,499:
end proc;
sundays(2013);</
{{Out|Output}}
<pre>
Line 3,346 ⟶ 3,517:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Table[Last@
DayRange[{year, i},
DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i,
12}]
LastSundays[2013]</
{{out}}
<pre>{{2013, 1, 27}, {2013, 2, 24}, {2013, 3, 31}, {2013, 4, 28}, {2013, 5,
Line 3,358 ⟶ 3,529:
=={{header|Nim}}==
<
const
Line 3,371 ⟶ 3,542:
var date = initDateTime(lastDay, month, year, 0, 0, 0)
date = date - days(DayDiffs[date.weekday])
echo date.format("yyyy-MM-dd")</
Sample usage:
<pre>./lastsunday 2013
Line 3,388 ⟶ 3,559:
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
let is_leap_year y =
(* See OCaml solution on Rosetta Code for
Line 3,430 ⟶ 3,601:
2 -> print_last_sundays( int_of_string (Sys.argv.(1)));
|_ -> invalid_arg "Please enter a year";
</syntaxhighlight>
Sample usage:
<pre> ocaml sundays.ml 2013
Line 3,447 ⟶ 3,618:
=={{header|Oforth}}==
<
: lastSunday(y)
Line 3,454 ⟶ 3,625:
Date newDate(y, m, Date.DaysInMonth(y, m))
while(dup dayOfWeek Date.SUNDAY <>) [ addDays(-1) ] println
] ;</
{{out}}
Line 3,474 ⟶ 3,645:
=={{header|PARI/GP}}==
<
njd(D) =
{
Line 3,498 ⟶ 3,669:
}
for (m=1, 12, a=njd([2013,m+1,0]); print(njdate(a-(a+6)%7)))</
Output:<pre>
Line 3,516 ⟶ 3,687:
=={{header|Perl}}==
<
use strict ;
use warnings ;
Line 3,529 ⟶ 3,700:
my $ymd = $date->ymd ;
print "$ymd\n" ;
}</
{{out}}
<pre>2013-01-27
Line 3,547 ⟶ 3,718:
=={{header|Phix}}==
Requires 0.8.1 (day_of_week() is now ISO 8601 compliant)
<!--<
<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,572 ⟶ 3,743:
<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>
<!--</
{{out}}
<pre>
Line 3,590 ⟶ 3,761:
=={{header|PHP}}==
<
// Created with PHP 7.0
Line 3,605 ⟶ 3,776:
printLastSundayOfAllMonth($argv[1]);
</syntaxhighlight>
{{out}}
<pre>
Line 3,622 ⟶ 3,793:
=={{header|PicoLisp}}==
<
(for M 12
(prinl
Line 3,628 ⟶ 3,799:
(find '((D) (= "Sunday" (day D)))
(mapcar '((D) (date Y M D)) `(range 31 22)) )
"-" ) ) ) )</
Test:
<
2013-01-27
2013-02-24
Line 3,642 ⟶ 3,813:
2013-10-27
2013-11-24
2013-12-29</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function last-dayofweek {
param(
Line 3,659 ⟶ 3,830:
}
last-dayofweek 2013 "Sunday"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 3,679 ⟶ 3,850:
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">
function Get-Date0fDayOfWeek
{
Line 3,777 ⟶ 3,948:
}
}
</syntaxhighlight>
The default is to return <code>[DateTime]</code> objects:
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday
</syntaxhighlight>
{{Out}}
<pre>
Line 3,798 ⟶ 3,969:
</pre>
Return the <code>[DateTime]</code> objects as strings (using the default string format):
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString
</syntaxhighlight>
{{Out}}
<pre>
Line 3,817 ⟶ 3,988:
</pre>
Return the <code>[DateTime]</code> objects as strings (specifying the string format):
<syntaxhighlight lang="powershell">
1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString -Format yyyy-MM-dd
</syntaxhighlight>
{{Out}}
<pre>
Line 3,837 ⟶ 4,008:
=={{header|PureBasic}}==
<
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
NewList d.i()
Line 3,870 ⟶ 4,041:
EndIf
Print("...End")
Input()</
{{out}}
<pre>Input Year [ 1971 < y < 2038 ]: 2013
Line 3,889 ⟶ 4,060:
=={{header|Python}}==
<
import sys
import calendar
Line 3,903 ⟶ 4,074:
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))
</syntaxhighlight>
<b>Output</b>:
<syntaxhighlight lang="text">
2013-Jan-27
2013-Feb-24
Line 3,919 ⟶ 4,090:
2013-Nov-24
2013-Dec-29
</syntaxhighlight>
=={{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
<syntaxhighlight lang="qbasic">
' PROGRAM Last Sundays in Quick BASIC 4.5 (LASTSQB1)
' This program will calculate the last Sundays of each month in a given year.
Line 4,047 ⟶ 4,218:
END FUNCTION
</syntaxhighlight>
{{out}}
Line 4,069 ⟶ 4,240:
==={{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.
<syntaxhighlight lang="qbasic">
OPTION EXPLICIT
Line 4,122 ⟶ 4,293:
LastSundayOfMonth = iLSoM
END FUNCTION
</syntaxhighlight>
{{out}}
Line 4,144 ⟶ 4,315:
=={{header|Quackery}}==
<
dup 4 / over +
over 100 / -
Line 4,191 ⟶ 4,362:
[ 0 lastwkdays ] is lastsundays ( year --> )
2013 lastsundays</
{{out}}
Line 4,209 ⟶ 4,380:
=={{header|R}}==
<
last_sundays <- function(year) {
for (month in 1:12) {
Line 4,224 ⟶ 4,395:
}
last_sundays(2004)
</syntaxhighlight>
{{out}}
<pre>
Line 4,242 ⟶ 4,413:
=={{header|Racket}}==
<
#lang racket
(require srfi/19 math)
Line 4,284 ⟶ 4,455:
(for ([d (last-sundays 2013)])
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
</syntaxhighlight>
{{out}}
<pre>
Line 4,305 ⟶ 4,476:
{{works with|rakudo|2018.03}}
<syntaxhighlight lang="raku"
for 1..12 -> $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;
}
}</
{{out|input=2018}}
Line 4,327 ⟶ 4,498:
=={{header|REBOL}}==
<
last-sundays-of-year: function [
Line 4,343 ⟶ 4,514:
foreach sunday last-sundays-of-year to-integer system/script/args [print sunday]
</syntaxhighlight>
{{out}}
<pre>./last-sundays.reb 2013
Line 4,365 ⟶ 4,536:
except for the innards of the first '''DO''' loop. <br><br>
The '''lastDOW''' subroutine can be used for any day-of-the-week for any month for any year.
<
parse arg yyyy
do j=1 for 12
Line 4,443 ⟶ 4,614:
.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; exit 13 /*... then exit. */</
{{out|output|text= when using the default input (the current year, 2013):}}
<pre>
Line 4,461 ⟶ 4,632:
=={{header|Ring}}==
<
see "What year to calculate (yyyy) : "
give year
Line 4,480 ⟶ 4,651:
next
next
</syntaxhighlight>
Output:
<pre>
Line 4,497 ⟶ 4,668:
2013-11-24
2013-12-29
</pre>
=={{header|RPL}}==
<code>WKDAY</code> is defined at [[Day of the week#RPL|Day of the week]]
{{works with|HP|48}}
≪ → year
≪ { }
.02 .13 '''FOR''' month
1 month .13 == DUP .01 month IFTE SWAP year + 1000000 / + + <span style="color:grey">@ Generate 1st day of the following month</span>
DUP <span style="color:blue">WKDAY</span> NEG DATE+ +
.01 '''STEP'''
2 FIX <span style="color:grey">@ Display October Sunday as ##.10 and not as ##.1</span>
≫ ≫ '<span style="color:blue">LSTSU</span>' STO
2013 <span style="color:blue">LSTSU</span>
{{out}}
<pre>
1: { 27.01 24.02 24.03 28.04 26.05 30.06 28.07 25.08 29.09 27.10 24.11 29.12 }
</pre>
=={{header|Ruby}}==
<
def last_sundays_of_year(year = Date.today.year)
Line 4,509 ⟶ 4,698:
end
puts last_sundays_of_year(2013)</
{{out}}
Line 4,529 ⟶ 4,718:
=={{header|Run BASIC}}==
<
print "Last Sundays in ";year;" are:"
dim month(12)
Line 4,546 ⟶ 4,735:
if x = 4 then print year ; "-";right$("0"+str$(n),2);"-" ; i
next
next</
<pre>
What year to calculate (yyyy) : ?2013
Line 4,564 ⟶ 4,753:
=={{header|Rust}}==
<
use time::{Date, Duration};
Line 4,577 ⟶ 4,766:
println!("{}", date - days_back);
});
}</
{{out}}
<pre>
Line 4,595 ⟶ 4,784:
=={{header|S-BASIC}}==
<
rem - return p mod q
function mod(p, q = integer) = integer
Line 4,666 ⟶ 4,855:
print shortmonth(m);" ";lastkday(SUNDAY, m, y)
next m
end</
{{out}}
<pre>
Line 4,684 ⟶ 4,873:
=={{header|Scala}}==
<
import java.util.Calendar._
val cal = getInstance
Line 4,698 ⟶ 4,887:
val fmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
println(lastSundaysOf(year).map(fmt.format) mkString "\n")
}</
===Java 8===
<
def lastSundaysOf(year: Int) = (1 to 12).map{month =>
import java.time._; import java.time.temporal.TemporalAdjusters._
Line 4,707 ⟶ 4,896:
val year = args.headOption.map(_.toInt).getOrElse(java.time.LocalDate.now.getYear)
println(lastSundaysOf(year) mkString "\n")
}</
=={{header|Seed7}}==
Line 4,714 ⟶ 4,903:
Applicable to any day of the week, cf. [[http://rosettacode.org/wiki/Last_Friday_of_each_month#Seed7]].
<
include "time.s7i";
include "duration.s7i";
Line 4,743 ⟶ 4,932:
end for;
end if;
end func;</
{{out}} when called with <tt>s7 rosetta/lastWeekdayInMonth 7 2013</tt>:
Line 4,762 ⟶ 4,951:
=={{header|Sidef}}==
<
var (year=2016) = ARGV.map{.to_i}...
Line 4,776 ⟶ 4,965:
say date.ymd;
}</
{{out}}
<pre>
Line 4,795 ⟶ 4,984:
=={{header|Smalltalk}}==
<
Pharo Smalltalk
Line 4,805 ⟶ 4,994:
thenSelect: [ :each |
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
</syntaxhighlight>
{{out}}
<pre>
Line 4,813 ⟶ 5,002:
=={{header|Stata}}==
<
args year
clear
Line 4,839 ⟶ 5,028:
| 24nov2013 |
| 29dec2013 |
+-----------+</
=={{header|Swift}}==
<
func lastSundays(of year: Int) -> [Date] {
Line 4,872 ⟶ 5,061:
dateFormatter.dateStyle = .short
print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))</
{{out}}
<pre>
Line 4,890 ⟶ 5,079:
=={{header|Tcl}}==
<
if {$year eq ""} {
set year [clock format [clock seconds] -gmt 1 -format "%Y"]
Line 4,903 ⟶ 5,092:
return $result
}
puts [join [lastSundays {*}$argv] "\n"]</
{{out}}
When called as: “<code>tclsh lastSundays.tcl 2013</code>” (or with the year argument omitted during 2013)
Line 4,926 ⟶ 5,115:
This uses the programs awk and cal, which are usually installed on any POSIXlike system.
<
local y=$1
for (( m=1; m<=12; ++m )); do
cal $m $y | awk -vy=$y -vm=$m '/^.[0-9]/ {d=$1} END {print y"-"m"-"d}'
done
}</
{{Out}}
Line 4,950 ⟶ 5,139:
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
strYear = WScript.StdIn.ReadLine
Line 4,957 ⟶ 5,146:
WScript.Echo d - Weekday(d) + 1
Next
</syntaxhighlight>
=={{header|Wren}}==
{{libheader|Wren-date}}
<
import "./date" for Date
var args = Process.arguments
Line 4,981 ⟶ 5,170:
System.print(dt.addDays(-wd))
}
}</
{{out}}
<pre>
$ wren
The dates of the last Sundays in the month for 2013 are:
2013-01-27
Line 5,000 ⟶ 5,189:
2013-12-29
$ wren
The dates of the last Sundays in the month for 2020 are:
2020-01-26
Line 5,014 ⟶ 5,203:
2020-11-29
2020-12-27
</pre>
=={{header|XPL0}}==
<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
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400)/7);
];
int Year, Month, LastDay, WD;
[Year:= IntIn(8); \from command line
for Month:= 1 to 12 do
[LastDay:= WeekDay(Year, Month+1, 1) - WeekDay(Year, Month, 28);
if LastDay < 0 then LastDay:= LastDay + 7;
LastDay:= LastDay + 27; \ = number of days in Month
WD:= WeekDay(Year, Month, LastDay);
LastDay:= LastDay - WD;
IntOut(0, Year); ChOut(0, ^-);
if Month < 10 then ChOut(0, ^0); IntOut(0, Month); ChOut(0, ^-);
IntOut(0, LastDay); CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
</pre>
|