Dates and times
The classes of java.time never change: every method gives a new object. Dates, times, formats, differences and the first Sunday of a month.
What you will learn#
LocalDate,LocalTime,LocalDateTimeandDuration,- formatting and parsing with a pattern,
- the days between two dates,
- finding the first Sunday of a month.
The program#
# Tutorial 5: dates and times - java.time
load "java.ring"
using {
"java.time"
"java.time.format"
"java.time.temporal"
}
LocalDate = new LocalDate
LocalDateTime = new LocalDateTime
Duration = new Duration
Period = new Period
DateTimeFormatter = new DateTimeFormatter
ChronoUnit = new ChronoUnit
DayOfWeek = new DayOfWeek
# a date: the objects of java.time never change, every method gives a new one
oDate = LocalDate.of(2024,2,29)
? oDate.toString()
? oDate.plusDays(1).toString()
? oDate.plusYears(1).toString()
? oDate.getDayOfWeek().toString()
? oDate.isLeapYear()
? oDate.lengthOfMonth()
# formatting and parsing
oFormat = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy")
? oDate.format(oFormat)
oParsed = LocalDate.parse("2025-12-25")
? oParsed.getMonth().toString()
# the days between two dates
? ChronoUnit.DAYS.between(oDate,oParsed)
oPeriod = Period.between(oDate,oParsed)
? "" + oPeriod.getYears() + " years, " + oPeriod.getMonths() + " months, " + oPeriod.getDays() + " days"
# time of day and durations
oMeeting = LocalDateTime.of([2024,6,15,9,30])
? oMeeting.toString()
oEnd = oMeeting.plus(Duration.ofMinutes(135))
? oEnd.format(DateTimeFormatter.ofPattern("HH:mm"))
? Duration.between(oMeeting,oEnd).toMinutes()
# the first Sunday of a month
oFirst = LocalDate.of(2024,7,1)
while oFirst.getDayOfWeek().equals(DayOfWeek.SUNDAY) = 0
oFirst = oFirst.plusDays(1)
end
? "first Sunday of July 2024: " + oFirst.toString()
# today is different every day: only its shape is shown
? len(LocalDate.now().toString())2024-02-29
2024-03-01
2025-02-28
THURSDAY
1
29
Thursday, 29 February 2024
DECEMBER
665
1 years, 9 months, 26 days
2024-06-15T09:30
11:45
135
first Sunday of July 2024: 2024-07-07
10How it works#
LocalDate.of(2025, 1, 31) makes a date. plusMonths(1) does not change it, it returns a new date (2025-02-28: the end of the month is respected). DateTimeFormatter.ofPattern("dd/MM/yyyy") formats and parses. ChronoUnit.DAYS.between(a, b) counts days. TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY) finds a weekday.
Exercises#
- How many days until the end of this year?
- On which weekday were you born?
- Print the dates of every Monday in a month.