Getting Current Date Time in Java
As a Java programmer, you will often need to work with date and time. In this post, we will learn how to get the current time of the day in Java applications.
Join the DZone community and get the full member experience.
Join For FreeAs a Java programmer, you will often need to work with date and time. In this post, we will learn how to get the current time of the day in Java applications. In Java, there are several ways for this and the primary classes that programmers typically use are the Date and Calendar classes. You can use both the classes to calculate the current time of the day and then use the SimpleDateFormat class to format the time according to your requirements.
Using the Date and Calendar Classes
To calculate the current time you create a Date object, specify a format to present the current time of the day, and finally use the SimpleDateFormat class to format the time as you specified.
Here is the code.
. . .
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
. . . .
In the code above, we created a Date
object and specified the format for the time. In the format string, the lower case hh
represents a 12 hour format while mm
and ss
represents minutes in hour and seconds in minutes respectively. Also, a
in the format string is the am/pm marker. We then created a SimpleDateFormat
object initialized with the format string and called the format()
method on it passing the Date
object. The format()
method returns the current time in the format we specified.
Using the Calendar class is equally simple. Here is the code.
. . .
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
. . .
In the code above, we called the getInstance()
factory method of the Calendar
class to obtain a Calendar
object and then called the getTime()
method on it. This method returns a Date
object. The remaining code is the same as I explained in the preceding Date example. The only difference you should observe is the format string. Here we specified hour as HH
(Upper case) which will give us the time in 24 hour format.
Here is the complete code.
CurrentTimeDateCalendar
package guru.springframework.blog.currenttime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
}
We will next write a test class.
CurrentTimeDateCalendarTest
package guru.springframework.blog.currenttime;
import org.junit.Test;
import static org.junit.Assert.*;
public class CurrentTimeDateCalendarTest {
@Test
public void testGetCurrentTimeUsingDate() throws Exception {
CurrentTimeDateCalendar.getCurrentTimeUsingDate();
}
@Test
public void testGetCurrentTimeUsingCalendar() throws Exception {
CurrentTimeDateCalendar.getCurrentTimeUsingCalendar();
}
}
The output is this.
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running guru.springframework.blog.currenttime.CurrentTimeDateCalendarTest
Current time of the day using Date - 12 hour format: 11:13:01 PM
Current time of the day using Calendar - 24 hour format: 23:13:01
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec - in guru.springframework.blog.currenttime.CurrentTimeDateCalendarTest
By now, you might be thinking that calculating current time in Java can never be easier. But the Date andCalendar classes have some inherent disadvantages. When you start developing enterprise applications, the disadvantages become more obvious. Primarily, both the classes are not thread-safe, which might lead to concurrency issues. Also, both the classes have the limitation of calculating time to milliseconds only. In mission-critical enterprise applications, it is often required to represent time to nanosecond precision.
In addition, even though the Date class is not itself deprecated, due to poor API design most of its constructors and methods are now deprecated. Because of such issues, enterprise application developers turned toward third-party specialized date and time APIs, particularly Joda-Time.
Using java.time
The Java specification team of Oracle realized the limitations of the in-built date and time handling API and to provide a more efficient API introduced the java.time package in the new Java SE 8. This project is developed jointly by Oracle and Stephen Colebourne, the author of Joda-Time. The new java.time API “is inspired by Joda-Time“.
Calculating Time of the Default Time Zone
The java.time package have several classes to work with date and time. Let’s start with some code to calculate the current time of the default time zone.
. . .
public static void getCurrentTime(){
System.out.println("-----Current time of your time zone-----");
LocalTime time = LocalTime.now();
System.out.println("Current time of the day: " + time);
}
. . .
As you can observe, the code is pretty straight forward. We called the now()
method of LocalTime
that returns a LocalTime
object. This is an immutable object that represent a time without a date and a time-zone in the ISO-8601 calendar system.
The output of the code is.
-----Current time of your time zone-----
Current time of the day: 23:13:01.762
In the output above, observe that the time is represented to nanosecond precision.
Calculating Time of a Different Time Zone
The java.time package provides classes that you can use to get the current time of a different time zone. As an example, if you are located in your default time zone and you want the current time of the day of a different time zone, say America/Los_Angeles, you can use the following classes:
- ZoneId: Represents a particular time zone.
- DateTimeFormatter: Similar to the SimpleDateFormat class we discussed earlier, this class is a formatter for parsing and printing date-time objects.
The code to calculate the current time of a different time zone is this.
. . .
public static void getCurrentTimeWithTimeZone(){
System.out.println("-----Current time of a different time zone using LocalTime-----");
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
LocalTime localTime=LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime=localTime.format(formatter);
System.out.println("Current time of the day in Los Angeles: " + formattedTime);
}
. . .
In Line 4 – Line 5, we created a ZoneId
object to represent the America/Los_Angeles
time zone and then obtained the current time of the time zone by calling the now()
method passing the ZoneId
. The LocalTime
object that the now()
method returns holds the current time of the day of America/Los_Angeles
. From Line 6 – Line 8, we formatted the time into 24 hour format using DateTimeFormatter
and printed out the formatted time.
The output of the code is.
-----Current time of a different time zone using LocalTime-----
Current time of the day in Los Angeles: 16:29:23
Calculating Time of a Different Time Offset
Time offset is the amount of time in hours and minutes added to or subtracted from Coordinated Universal Time (UTC). The java.time package provides the ZoneOffset class to calculate the current time of the day of a different time offset.
The code to use the ZoneOffset class is this.
. . .
public static void getCurrentTimeWithOffset(){
System.out.println("-----Current time of different offset-----");
ZoneOffset zoneOffset = ZoneOffset.of("-08:00");
ZoneId zoneId=ZoneId.ofOffset("UTC", zoneOffset);
LocalTime offsetTime = LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
String formattedTime=offsetTime.format(formatter);
System.out.println("Current time of the day with offset -08:00: " + formattedTime);
}
. . .
In the code above, we created a ZoneOffset
object in Line 4 to represent the -8:00 time offset. In Line 5 we created a ZoneId
object initialized with the ZoneOffset
object. The remaining code from Line 6 to Line 9 uses a LocalTime
object initialized with the ZoneId
and a DateTimeFormatter
object to format the time in the 12 – hour format with the am/pm marker
The output of the preceding code is.
-----Current time of different offset-----
Current time of the day with offset -08:00: 03:29 PM
The complete code of the snippets we discussed is this.
package guru.springframework.blog.currenttime;
import java.time.*;
import java.time.format.DateTimeFormatter;
public class CurrentTimeJava8 {
public static void getCurrentTime(){
System.out.println("-----Current time of your time zone-----");
LocalTime time = LocalTime.now();
System.out.println("Current time of the day: " + time);
}
public static void getCurrentTimeWithTimeZone(){
System.out.println("-----Current time of a different time zone using LocalTime-----");
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
LocalTime localTime=LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime=localTime.format(formatter);
System.out.println("Current time of the day in Los Angeles: " + formattedTime);
}
public static void getCurrentTimeWithOffset(){
System.out.println("-----Current time of different offset-----");
ZoneOffset zoneOffset = ZoneOffset.of("-08:00");
ZoneId zoneId=ZoneId.ofOffset("UTC", zoneOffset);
LocalTime offsetTime = LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
String formattedTime=offsetTime.format(formatter);
System.out.println("Current time of the day with offset -08:00: " + formattedTime);
}
}
Let’s write a test class to see the code in action.
package guru.springframework.blog.currenttime;
import org.junit.Test;
import static org.junit.Assert.*;
public class CurrentTimeJava8Test {
@Test
public void testGetCurrentTime() throws Exception {
CurrentTimeJava8.getCurrentTime();
}
@Test
public void testGetCurrentTimeWithTimeZone() throws Exception {
CurrentTimeJava8.getCurrentTimeWithTimeZone();
}
@Test
public void testGetCurrentTimeWithOffset() throws Exception {
CurrentTimeJava8.getCurrentTimeWithOffset();
}
}
The output I got on running the test using Maven is shown below, which obviously will differ based on your current time and time zone.
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running guru.springframework.blog.currenttime.CurrentTimeJava8Test
-----Current time of your time zone-----
Current time of the day: 06:59:52.803
-----Current time of a different time zone using LocalTime-----
Current time of the day in Los Angeles: 18:29:52
-----Current time of different offset-----
Current time of the day with offset -08:00: 05:29 PM
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.337 sec - in guru.springframework.blog.currenttime.CurrentTimeJava8Test
Summary
In terms of working with time in Java, this post has only scratched the surface. The java.time package has an extensive set of classes that simplifies working with date and time. However, you will also encounter the Date and Calendar classes and the Joda-Time API when you work on legacy applications. But, with the powerful features built in java.time, you can easily convert your legacy date and time calculation code to java.time. Go ahead and explore the java.time API, which is very well documented and easy to use.
Keep in mind when you’re using the local time options, Java is going through the JVM to talk to whatever machine it is running on. This is how Java is determines the time and the locale of time operations. Thus, your code can produce different results when running on different machines. As a word of caution, when you’re working on small applications, often you won’t need to worry about time timezone. But in larger applications, you will. You will need to make your code aware of the timezone. Many developers overlook the timezone component, then run into problems later as their application grows.
Published at DZone with permission of John Thompson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments