Java Time Functions: Complete Guide

In Java, you can work with time and dates using classes such as java.util.Date and java.util.Calendar, as well as the java.time package introduced in Java 8.

Here are examples of how to use common time functions.

  1. Get the current date and time.
import java.util.Date;

Date currentDate = new Date();
System.out.println(currentDate);
  1. Format the date:
import java.text.SimpleDateFormat;
import java.util.Date;

Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate);
  1. Obtain specific date and time:
import java.util.Calendar;

Calendar calendar = Calendar.getInstance();
calendar.set(2022, Calendar.OCTOBER, 1);
Date specificDate = calendar.getTime();
System.out.println(specificDate);
  1. Calculate the difference in dates:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate date1 = LocalDate.of(2022, 1, 1);
LocalDate date2 = LocalDate.of(2022, 12, 31);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println(daysBetween);
  1. Formatting date and time (Java 8 and above):
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println(formattedDateTime);

Please note that the java.util.Date and java.util.Calendar classes before Java 8 have limited functionality in handling date and time, while the java.time package offers a more extensive and user-friendly API.

bannerAds