Working with System Time and Custom Formatting in Java
Manipulating system time and specifying its output format in Java is efficient handled using the java.time API. The LocalDateTime class represents date and time with out a timezone, while DateTimeFormatter controls the display pattern.
To capture the current moment and format it, use LocalDateTime.now() and a formatter.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class SystemTimeFormatter {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(pattern);
System.out.println(formattedNow);
}
}
This code prints the current time in a year-month-day hour:minute:second layout.
You can also calculate past or future times. To get a date two days prior to the current date:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class PastTimeCalculation {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
LocalDateTime twoDaysAgo = current.minusDays(2);
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String result = twoDaysAgo.format(myFormat);
System.out.println(result);
}
}
The minusDays(int) method subtracts the specified number of days. Similar methods like minusHours(int), minusMinutes(long), and minusSeconds(long) are available for other time units.
Customize the format string passed to DateTimeFormatter.ofPattern() to meet specific requiremants. Common pattern letters include yyyy for year, MM for month, dd for day, HH for 24-hour clock hour, mm for minute, and ss for second.