Code Examples In Java
Introduction
Date and time management is a crucial aspect of many web applications, whether scheduling events, logging user activity, or displaying localized times for a global audience.
The modern java.time package, introduced in Java 8, offers a comprehensive and intuitive API for handling date and time. It replaces the older java.util.Date and java.util.Calendar classes with a cleaner, more consistent approach. This package includes classes for representing date and time (LocalDate, LocalTime, LocalDateTime), working with timezones (ZonedDateTime, ZoneId), and manipulating Unix timestamps using Instant.
Get Current Time
Retrieving the current time is a fundamental requirement in many Java applications, whether it’s for logging events, scheduling tasks, or displaying timestamps.
With the java.time package, you can obtain the current date, time, or both using classes like LocalDate, LocalTime, LocalDateTime, and Instant. These classes make it easy to retrieve, format, and manipulate time values for various use cases.
Method:
1// import java.time.LocalDateTime;
2// Recommanded for Java 8 and later
3LocalDateTime.now()
Example:
1import java.time.LocalDateTime;
2
3public class Main {
4 public static void main(String[] args) {
5 LocalDateTime currentDateTime = LocalDateTime.now();
6 System.out.println("Current Date and Time: " + currentDateTime);
7 }
8}
Result:
1Current Date and Time: 2024-10-04T23:35:50.103060900
Get Unix Timestamp
Unix timestamps are a standard way of representing time as the number of seconds (or milliseconds) elapsed since the Unix epoch, which is January 1, 1970, at 00:00:00 UTC. They are widely used in web development for logging, scheduling, and synchronizing time across systems due to their simplicity and consistency.
Java provides robust support for working with Unix timestamps, particularly through the java.time package introduced in Java 8. The Instant class from this package is specifically designed to represent timestamps and makes it easy to retrieve the current Unix timestamp or convert between timestamps and other date-time representations.
Method:
1System.currentTimeMillis()
2
3// using java.time.Instant
4Instant.now().getEpochSecond();
5
6// import java.time.LocalDateTime;
7LocalDateTime.toEpochSecond(ZoneOffset offset)
8
9// import java.time.ZonedDateTime;
10ZonedDateTime.toEpochSecond();
Example:
1import java.time.Instant;
2import java.time.LocalDateTime;
3import java.time.ZoneId;
4import java.time.ZoneOffset;
5
6public class Main {
7 public static void main(String[] args) {
8 // Get Unix timestamp in seconds using System.currentTimeMillis
9 long unixTimestamp = System.currentTimeMillis() / 1000L;
10 System.out.println("Unix Timestamp: " + unixTimestamp);
11
12 // Get Unix timestamp in seconds using Instant
13 long unixTimestampUseInstant = Instant.now().getEpochSecond();
14 System.out.println("Unix Timestamp using Instant: " + unixTimestampUseInstant);
15
16 // Get Unix timestamp in seconds using LocalDateTime and ZonedDateTime
17 // Define a specific date and time with Year, Month, Day, Hour, Minute, Second
18 LocalDateTime dateTime = LocalDateTime.of(2024, 10, 5, 12, 30, 45);
19 ZoneOffset offset = ZoneOffset.UTC; // or ZoneOffset.ofHours(-5) for UTC-5
20 // Convert the LocalDateTime to a Unix timestamp
21 long unixTimestampUseLocalDateTime = dateTime.toEpochSecond(offset);
22 System.out.println("Unix Timestamp using LocalDateTime: " + unixTimestampUseLocalDateTime);
23
24 // Convert to Unix timestamp using ZonedDateTime
25 long unixTimestampUseZonedDateTime = dateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
26 System.out.println("Unix Timestamp using ZonedDateTime: " + unixTimestampUseZonedDateTime);
27 }
28}
Result:
1Unix Timestamp: 1733407925
2Unix Timestamp using Instant: 1733407925
3Unix Timestamp using LocalDateTime: 1728131445
4Unix Timestamp using ZonedDateTime: 1728102645
Construct New Time
Creating new date and time objects is a core aspect of many Java applications, enabling developers to represent specific moments in time, schedule events, or perform date arithmetic.
Java provides powerful and flexible tools for constructing date and time values through the modern java.time package, introduced in Java 8, which replaces the older java.util.Date and Calendar classes
Method:
1// using java.time.LocalTime
2LocalTime.of(int hour, int minute, int second)
3
4// using java.time.LocalDateTime
5LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second)
6LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
7
8// using java.time.ZonedDateTime, with timezone
9ZonedDateTime.of(int year, int month, int dayOfMonth, int hour,
10 int minute, int second, int nanoOfSecond, ZoneId zone)
11
12ZonedDateTime.parse(CharSequence text, DateTimeFormatter formatter)
Example:
1import java.time.LocalDateTime;
2import java.time.LocalTime;
3import java.time.ZoneId;
4import java.time.ZonedDateTime;
5import java.time.format.DateTimeFormatter;
6
7public class Main {
8 public static void main(String[] args) {
9 // Create a specific time (hour, minute, second)
10 LocalTime time = LocalTime.of(14, 30, 45);
11 System.out.println("Specific Time: " + time);
12
13 // Create a LocalDateTime (year, month, day, hour, minute, second)
14 LocalDateTime localDateTime = LocalDateTime.of(2024, 5, 15, 14, 30, 45);
15 System.out.println("LocalDateTime: " + localDateTime);
16
17 // Create a LocalDateTime using parse
18 // Define the date-time string
19 String dateTimeString = "2024-11-05 14:30:45";
20 // Define the formatter matching the input string pattern
21 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
22 // Parse the string into a LocalDateTime object
23 LocalDateTime localDateTimeUseParse = LocalDateTime.parse(dateTimeString, formatter);
24 System.out.println("LocalDateTime using parse: " + localDateTimeUseParse);
25
26 // Create time with timezone
27 ZoneId zone = ZoneId.of("America/New_York");
28 ZonedDateTime zonedDateTime = ZonedDateTime.of(2024, 5, 15, 14, 30, 45, 0, zone);
29 System.out.println("ZonedDateTime: " + zonedDateTime);
30
31 // Create time with timezone using parse
32 String dateTimeStringWithTimeZone = "2024-11-05 14:30:45 America/New_York";
33 DateTimeFormatter formatterWithTimeZone = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
34 ZonedDateTime zonedDateTimeUseParse = ZonedDateTime.parse(dateTimeStringWithTimeZone, formatterWithTimeZone);
35 System.out.println("ZonedDateTime using parse: " + zonedDateTimeUseParse);
36 }
37}
Result:
1Specific Time: 14:30:45
2LocalDateTime: 2024-05-15T14:30:45
3LocalDateTime using parse: 2024-11-05T14:30:45
4ZonedDateTime: 2024-05-15T14:30:45-04:00[America/New_York]
5ZonedDateTime using parse: 2024-11-05T14:30:45-05:00[America/New_York]
Convert Unix timestamp to Readable Date Time
Unix timestamps, representing the number of seconds since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are commonly used in programming for their simplicity and efficiency.
However, they are not human-readable, making it necessary to convert them into a readable date and time format for display, logging, or reporting purposes
In Java, the modern java.time package introduced in Java 8 provides powerful and intuitive tools for converting Unix timestamps into readable date-time objects. The Instant class represents a point in time in UTC, which can then be converted into other date-time classes such as LocalDateTime or ZonedDateTime for localized and formatted displays.
Method:
1// using java.time.LocalDateTime
2LocalDateTime.ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset)
3
4// using java.time.Instant
5Instant.ofEpochSecond(long epochSecond, long nanoAdjustment)
6Instant.atZone(ZoneId zone)
Example:
1import java.time.Instant;
2import java.time.LocalDateTime;
3import java.time.ZoneId;
4import java.time.ZoneOffset;
5import java.time.ZonedDateTime;
6
7public class Main {
8 public static void main(String[] args) {
9 // Define Unix timestamp (seconds since epoch)
10 long epochSecond = 1733406645L; // Example: December 5, 2024, 12:30:45 UTC
11 int nanoOfSecond = 0; // No additional nanoseconds
12
13 ZoneOffset offset = ZoneOffset.UTC; // UTC offset
14 LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
15 System.out.println("LocalDateTime: " + localDateTime);
16
17 // Using Instant
18 Instant instant = Instant.ofEpochSecond(epochSecond);
19 ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("UTC"));
20 System.out.println("ZonedDateTime: " + zonedDateTime);
21 }
22}
Result:
1LocalDateTime: 2024-12-05T13:50:45
2ZonedDateTime: 2024-12-05T13:50:45Z[UTC]
Convert Date Time to Unix timestamp
Converting date-time objects into Unix timestamps is a common operation in Java, often required for storing time values, performing calculations, or interacting with APIs and databases that use Unix time.
Java modern java.time package, introduced in Java 8, provides a clean and intuitive way to convert date-time objects to Unix timestamps.
Method:
1// using java.time.LocalDateTime;
2LocalDateTime.toEpochSecond(ZoneOffset offset)
3
4// using java.time.ZonedDateTime;
5ZonedDateTime.toEpochSecond();
6
7// using java.time.Instant
8Instant.toEpochMilli()
9Instant.toEpochSecond()
10Instant.getNano()
Example:
1import java.time.Instant;
2import java.time.LocalDateTime;
3import java.time.ZoneId;
4import java.time.ZoneOffset;
5import java.time.ZonedDateTime;
6
7public class Main {
8 public static void main(String[] args) {
9 // Using LocalDateTime
10 LocalDateTime localDateTime = LocalDateTime.of(2024, 5, 15, 14, 30, 45);
11 long epochSecondUseLocalDateTime = localDateTime.toEpochSecond(ZoneOffset.UTC);
12 System.out.println("Unix Timestamp using LocalDateTime: " + epochSecondUseLocalDateTime);
13
14 // Using ZonedDateTime
15 ZoneId zone = ZoneId.of("America/New_York");
16 ZonedDateTime zonedDateTime = ZonedDateTime.of(2024, 5, 15, 14, 30, 45, 0, zone);
17 long epochSecondUseZonedDateTime = zonedDateTime.toEpochSecond();
18 System.out.println("Unix Timestamp using ZonedDateTime: " + epochSecondUseZonedDateTime);
19
20 // Using Instant
21 Instant instant = Instant.now();
22 long epochMilliSecond = instant.toEpochMilli();
23 int nanoOfSecond = instant.getNano();
24
25 // Combine milliseconds and nanoseconds for a full timestamp
26 long timestampWithNanoseconds = epochMilliSecond * 1_000_000L + nanoOfSecond;
27 System.out.println("Unix Timestamp with Nanoseconds using Instant: " + timestampWithNanoseconds);
28 }
29}
Result:
1Unix Timestamp using LocalDateTime: 1715783445
2Unix Timestamp using ZonedDateTime: 1715797845
3Unix Timestamp with Nanoseconds using Instant: 1733414262260194900
Change Time Zone
Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
The modern java.time package, introduced in Java 8, offers comprehensive support for handling timezones through classes like ZonedDateTime and ZoneId. These classes allow you to create, convert, and format date-time values for specific timezones, manage daylight saving time (DST) transitions, and maintain time consistency across distributed systems.
Method:
1// Getting a Specific Time Zone
2ZoneId.of(String zoneId)
3
4// current date time in the specified time zone
5ZonedDateTime.now(ZoneId zone)
6
7// Change to different time zone
8ZonedDateTime.withZoneSameInstant(ZoneId zone)
Example:
1import java.time.ZoneId;
2import java.time.ZonedDateTime;
3
4public class Main {
5 public static void main(String[] args) {
6 // create a specific time zone
7 ZoneId zoneId = ZoneId.of("America/New_York");
8 System.out.println("Specific Time Zone: " + zoneId);
9
10 // Create a ZonedDateTime in a specific time zone
11 ZonedDateTime nyTime = ZonedDateTime.now(zoneId);
12 System.out.println("New York Time: " + nyTime);
13
14 // Convert to another time zone
15 ZonedDateTime tokyoTime = nyTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
16 System.out.println("Tokyo Time: " + tokyoTime);
17 }
18}
Result:
1Specific Time Zone: America/New_York
2New York Time: 2024-12-07T09:55:05.930513500-05:00[America/New_York]
3Tokyo Time: 2024-12-07T23:55:05.930513500+09:00[Asia/Tokyo]
Time Addition and Subtraction
Manipulating dates and times is a common requirement in many applications. The java.time package includes immutable classes like LocalDate, LocalTime, LocalDateTime, and ZonedDateTime that support date and time arithmetic. These classes provide methods for adding or subtracting days, months, years, hours, minutes, and more, ensuring that calculations are straightforward and accurate.
Method:
1// Use LocalDateTime or ZonedDateTime
2plusDays(long days); minusDays(long days)
3plusHours(long hours); minusHours(long hours)
4plusMinutes(long minutes); minusMinutes(long minutes)
5// ... plusXXX() and minusXXX()
6
7// Calculate time difference
8Duration.between(startDateTime, endDateTime)
9System.nanoTime();
Example:
1import java.time.Duration;
2import java.time.Instant;
3import java.time.LocalDateTime;
4
5public class Main {
6 public static void main(String[] args) {
7 // Create a LocalDateTime (year, month, day, hour, minute, second)
8 LocalDateTime localDateTime = LocalDateTime.of(2024, 5, 15, 14, 30, 45);
9 System.out.println("LocalDateTime: " + localDateTime);
10
11 // Add 10 days
12 LocalDateTime futureDate = localDateTime.plusDays(10);
13 System.out.println("Future Date: " + futureDate);
14
15 // Subtract 2 months
16 LocalDateTime pastDate = localDateTime.minusMonths(2);
17 System.out.println("Date 2 months ago: " + pastDate);
18
19 // Calc time cost
20 // Using System.nanoTime
21 long startTime = System.nanoTime();
22
23 try {
24 // Sleep for 1 second (1000 milliseconds)
25 Thread.sleep(1000);
26 } catch (InterruptedException e) {
27 // Handle exception if the thread is interrupted
28 System.out.println("Sleep was interrupted: " + e.getMessage());
29 }
30
31 long endTime = System.nanoTime();
32 long timeCost = endTime - startTime;
33 System.out.println("Time cost: " + timeCost + " nanoseconds");
34
35 // Using Duration.between
36 Instant start = Instant.now();
37
38 try {
39 // Sleep for 1 second (1000 milliseconds)
40 Thread.sleep(1000);
41 } catch (InterruptedException e) {
42 // Handle exception if the thread is interrupted
43 System.out.println("Sleep was interrupted: " + e.getMessage());
44 }
45
46 // End time
47 Instant end = Instant.now();
48
49 // Calculate time cost
50 Duration timeCostofDuration = Duration.between(start, end);
51 System.out.println("Time cost of duration: " + timeCostofDuration.toNanos() + " nanoseconds");
52 }
53}
Result:
1LocalDateTime: 2024-05-15T14:30:45
2Future Date: 2024-05-25T14:30:45
3Date 2 months ago: 2024-03-15T14:30:45
4Time cost: 1006239600 nanoseconds
5Time cost of duration: 1010175600 nanoseconds
Pause or sleep for a specific time
Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
The primary method for introducing delays is Thread.sleep(), which pauses the execution of the current thread for a specified duration in milliseconds.
Method:
1Thread.sleep(long millis)
Example:
1public class Main {
2 public static void main(String[] args) {
3 // Calc time cost
4 // Using System.nanoTime
5 long startTime = System.nanoTime();
6
7 try {
8 // Sleep for 1 second (1000 milliseconds)
9 Thread.sleep(1000);
10 } catch (InterruptedException e) {
11 // Handle exception if the thread is interrupted
12 System.out.println("Sleep was interrupted: " + e.getMessage());
13 }
14
15 long endTime = System.nanoTime();
16 long timeCost = endTime - startTime;
17 System.out.println("Time cost: " + timeCost + " nanoseconds");
18 }
19}
Result:
1Time cost: 1008910800 nanoseconds