java.time package, LocalDate, LocalDateTime, DateTimeFormatter, and String APIs
Logging
Log class should do ?java.time packagejava.util.Date and Calendar classes (which are deprecated)package fr.tbr.exercises.example;
import java.time.LocalDate;
import java.time.Month;
public class LocalDateExample {
public static void main(String[] args) {
// Get current date
LocalDate today = LocalDate.now();
System.out.println("Today: " + today);
// Create specific date
LocalDate birthday = LocalDate.of(1990, Month.JANUARY, 15);
System.out.println("Birthday: " + birthday);
// Parse from string
LocalDate parsed = LocalDate.parse("2025-10-06");
System.out.println("Parsed: " + parsed);
}
}
LocalDate today = LocalDate.now();
// Add/subtract days, months, years
LocalDate nextWeek = today.plusDays(7);
LocalDate nextMonth = today.plusMonths(1);
LocalDate lastYear = today.minusYears(1);
// Get specific values
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
String dayOfWeek = today.getDayOfWeek().toString();
// Check relationships
boolean isBefore = today.isBefore(nextWeek); // true
boolean isAfter = today.isAfter(lastYear); // true
import java.time.LocalDateTime;
import java.time.Month;
public class LocalDateTimeExample {
public static void main(String[] args) {
// Get current date and time
LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + now);
// Create specific date-time
LocalDateTime meeting = LocalDateTime.of(2025, Month.OCTOBER, 6, 14, 30);
System.out.println("Meeting: " + meeting);
// Manipulate date-time
LocalDateTime nextHour = now.plusHours(1);
LocalDateTime yesterday = now.minusDays(1);
System.out.println("Next hour: " + nextHour);
System.out.println("Yesterday: " + yesterday);
}
}
try{]catch(Exception ex){} construct : this is the way errors are handled in Java.
try{} block symbolizes a part of code critical enough
to
throw an exception.
catch(Exception e){} block allows to react while concretely
facing that exception
DateTimeFormatter to format and parse dates:import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// Predefined formatters
LocalDateTime now = LocalDateTime.now();
String iso = now.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(iso); // 2025-10-06T14:30:00
// Custom formatters
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss");
String formatted = now.format(customFormatter);
System.out.println(formatted); // 2025/10/06 - 14:30:00
// Parsing from String
LocalDate parsed = LocalDate.parse("2025-10-06");
LocalDateTime parsedCustom = LocalDateTime.parse("2025/10/06 - 14:30:00", customFormatter);
Period to calculate date-based differences:import java.time.LocalDate;
import java.time.Period;
LocalDate birthday = LocalDate.of(1990, 1, 15);
LocalDate today = LocalDate.now();
// Calculate age
Period age = Period.between(birthday, today);
System.out.println("Age: " + age.getYears() + " years, "
+ age.getMonths() + " months, "
+ age.getDays() + " days");
// Calculate days between dates
long daysBetween = birthday.until(today).getDays();
System.out.println("Days since birth: " + daysBetween);
yyyy-MM-ddLocalDate.parse()DateTimeParseException)try-catch to handle invalid inputyyyy-MM-dd)Period.between() and LocalDate.plusYears()String firstString = "Sample String";
String secondString = "Second String";
ConcatenationSystem.out.println("Testing concatenation");
String concatResult = firstString + " " + secondString;
System.out.println(concatResult);
System.out.println("Testing replacement");
concatResult = concatResult.replaceAll("St" , "" );
System.out.println(concatResult);
Immutability : While other objects are "mutable" (their internal values can change during the
program execution), Strings are immutable.
Format //Full spec here
//http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
String formattedString = String.format("%tD", new Date());
System.out.println(formattedString);
StringBuilder, which allows the developer to "build" a StringStringBuilder sb = new StringBuilder(concatResult);
stringBuilder.append("blah").append(" ").append(new Date());
Mutability : What is convenient with the StringBuilder, is that it is mutable.
It allows to pass the StringBuilder to methods, and it is modified by the operations done in the method Body
Text blocks make multi-line strings much cleaner:
String json = "{\n" +
" \"name\": \"Alice\",\n" +
" \"age\": 30,\n" +
" \"city\": \"Paris\"\n" +
"}";
String json = """
{
"name": "Alice",
"age": 30,
"city": "Paris"
}
""";
""" and preserve formatting automatically!
// SQL queries
String query = """
SELECT id, name, email
FROM users
WHERE status = 'ACTIVE'
ORDER BY created_at DESC
""";
// HTML templates
String html = """
<html>
<body>
<h1>Welcome, %s!</h1>
</body>
</html>
""".formatted(userName);
// JSON responses
String response = """
{"status": "success", "data": %s}
""".formatted(data);
// Closing """ determines the left margin
String text = """
Line 1 ← 4 spaces from margin
Line 2 ← 4 spaces from margin
"""; ← This position is the left edge
// Result has no leading spaces
// because content aligns with closing quotes
| Escape | Effect |
|---|---|
\ at end of line | Suppress newline (continue line) |
\s | Preserve trailing whitespace |
\"\"\" | Include triple quotes in text |
ModernLogger with the following method:public void log(String message){
//Implement using LocalDateTime and DateTimeFormatter
}
LocalDateTime.now() to get the current timestampyyyy/MM/dd - HH:mm:ss2025/10/06 - 14:30:00 : Your message hereyyyy-MM-dd format)