Hello everybody,
Michael here, and today I’ll be sharing a fun Java lesson on the use of dates and times in Java. I already covered date and time manipulation for both Python and R, but here’s the Java version of this concept.
Now, since the last time I posted a Java lesson, I got a new laptop, but I still plan to use NetBeans as my main IDE for these posts.
When working with dates and times in Java, keep in mind that unlike in Python, Java doesn’t have a single Date class/module that you can easily import or pip install. Java does have a java.time package which allows you to work with date/time manipulation. However, unlike with Python, you can’t import the whole package at once and expect to be able to use all of the package’s classes just like that. Rather, you’ll need to import all the package’s classes (the classes that you want to use) one by one-this is one of the major disadvantages of Java.
To start off our exploration of Java date-time manipulation, let’s first explore the Clock class of the java.time package. Some of the things that the Clock class can do is print out the current time (in both UTC and other time zones) and retrieve your current time zone-both of which would be useful when developing applications that deal with time zones. Execute this code and see what happens:
import java.time.Clock;
public class DateTime {
public static void main(String[] args)
{
Clock c = Clock.systemDefaultZone();
System.out.println(c);
}
}
SystemClock[America/Chicago]
Now, what exactly does this code do? Well, it creates an object of the Clock class and prints out the value of the object.
You’re likely wondering what systemDefaultZone is. It’s one of several methods in the Clock class. You can’t create an object of the Clock class on it’s own-by that I mean you can’t create a Clock object that looks like this: Clock c = Clock(). You’ll need to use of the class’s methods-in this case, I used the systemDefaultZone method. All this method does is print out the time zone your computer uses. Since I am in Nashville, TN right now, my system default [time] zone is [America/Chicago], as Chicago also uses Central Standard Time.
The Clock class has other methods, which you can find on this documentation from Oracle-https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html. Explore this website for links related to some of the other classes that I will be discussing in this post.
Next up, let’s discuss the LocalDate class. This class allows you to display dates, but not datetimes or time zones. To start exploring the LocalDate class, let’s first create a simple LocalDate object:
import java.time.LocalDate;
public class DateTime {
public static void main(String[] args)
{
LocalDate ld = LocalDate.now();
System.out.println(ld);
}
}
2021-11-15
In this example, I created a simple LocalDate object that prints out today’s date using the .now() method (I ran this code on November 15, 2021). Just as with the Clock class, whenever you create a new object of the LocalDate class, you’ll need to include a class method with your object creation; in this case, I used the now() method of the LocalDate class.
Now, let’s explore some more methods of the LocalDate class by executing this code:
import java.time.LocalDate;
public class DateTime {
public static void main(String[] args)
{
LocalDate ld = LocalDate.now();
System.out.println(ld.plusMonths(3));
System.out.println(ld.getDayOfWeek());
System.out.println(ld.isLeapYear());
System.out.println(ld.toEpochDay());
}
}
2022-02-15
MONDAY
false
18946
In this example, I still created a LocalDate object called ld that uses the LocalDate class’s .now() method. However, I added four output lines (referenced with System.out.println()) which generate four different outputs based on four different methods. Here’s an explanation of each output:
- The first output-
2022-02-15-was generated through theLocalDateclass’s.plusMonths()method. The.plusMonths()method takes in one parameter-an integer that tells Java how many months to add to the date in theLocalDateobject. In this case, I passed in 3 as the parameter of the.plusMonths()method, which tells Java to add 3 months to today’s date-the output is February 15, 2022. - The second output-
MONDAY-was generated through the.getDayOfWeek()method, which in this case retrieves the current date’s day of the week. November 15, 2021 is a Monday, therefore this method will returnMONDAY.- Recall that the current date in this example is November 15, 2021.
- The third output-
false-was generated through the.isLeapYear()method, which in this case returns eithertrueorfalsedepending on whether the current year is a leap year. Since 2021 isn’t a leap year, this method returnedfalse. - The fourth output-
18946-was generated through the interesting.toEpochDay()method. You wouldn’t need to use the.toEpochDay()method much, but I’ll discuss it here anyway. This method simply returns the number of days its been since January 1, 1970-the “epoch time” for computers. Why January 1, 1970? It’s basically an arbitrary date that serves as the “zero point” (or default time) for most operating systems.- On my old laptops, when the operating system was having issues, the system date would always be set to January 1, 1970.
Now that we’ve explored the LocalDate class a bit, let’s move on to the LocalTime class. LocalTime is basically the opposite of LocalDate since LocalTime only displays times and timestamps but no dates.
Let’s create a simple LocalTime object using the code below:
import java.time.LocalTime;
public class DateTime {
public static void main(String[] args)
{
LocalTime lt = LocalTime.now();
System.out.println(lt);
}
}
21:13:50.623089
Similar to the LocalDate example, I created a LocalTime object using the .now() method. And in case you hadn’t figured it out by now, you can’t create a LocalTime object without including a class method (just as you needed a class method for the Clock and LocalDate objects)
In this case, the LocalTime object I created printed out the current (at runtime) time as set on my laptop-21:13:50.623089. I ran the code at 9:13PM Central Standard Time, but Java will print out the time in 24-hour format (and 21 represents the 9PM hour).
Now, let’s explore four other methods of the LocalTime class (you’ll notice that this code looks syntactically similar to the code in the previous example):
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneOffset;
public class DateTime {
public static void main(String[] args)
{
LocalTime lt = LocalTime.now();
System.out.println(lt);
System.out.println(lt.plusHours(6));
System.out.println(lt.minusMinutes(45));
System.out.println(lt.toNanoOfDay());
System.out.println(lt.toEpochSecond(LocalDate.MAX, ZoneOffset.UTC));
}
}
21:35:06.320094400
03:35:06.320094400
20:50:06.320094400
77706320094400
31556889832772106
Now, just as I did with the four methods in the LocalDate example, let’s explore the four methods I used here:
- Below the
ltoutput, you’ll see the output03:35:06.320094400, which was generated from the.plusHours()method. This method takes in an integer parameter (6 in this case) and add that many hours to the current time-in this case, 6 hours from the current [run]time is 3:35AM. - The next output is
20:50:06.320094400, which was generated from the.minusMinutes()method. Like the.plusHours()method, the.minusMinutes()method takes in an integer (45 in this case) as the parameter. However, the.minusMinutes()method subtracts a certain amount of minutes from theLocalTimeobject-in this case, 45 minutes before the current [run]time is 10:50PM. - The next output is
77706320094400, which was generated from the.toNanoOfDay()method. This method returns the nanosecond of the current time. In this case, 9:35:06PM is roughly the 77.7 trillionth nanosecond of the day. If the current time was 12:00:00AM, the.toNanoOfDay()method would return 1, as this time would be the first nanosecond of the day.- Just so you know, 1 second is equal to a billion nanoseconds.
- The last output is
31556889832772106, which was generated from the.toEpochSecond()method. This method is conceptually similar to the.toEpochDay()method, since both methods return the amount of time in a certain unit (days or second) since January 1, 1970. However,.toEpochSecond()returns the amount of seconds that have passed since January 1, 1970 at 12:00:00AM, which in this case is roughly 31.6 quadrillion seconds.- The
ZoneOffsetclass was needed for the .toEpochDay()method, but don’t worry about it otherwise.
- The
Next up, let’s explore the LocalDateTime class. You might be able to figure out what this class does based off the class name alone, but in case you didn’t, this class displays date-time objects-which are objects that display dates and times (in the same string).
As I did for both LocalDate and LocalTime, I will create a simple object of the LocalDateTime class using the .now() method:
import java.time.LocalDateTime;
public class DateTime {
public static void main(String[] args)
{
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
}
}
2021-11-20T07:22:10.017889200
This example prints out the current date-time (at runtime)-November 20, 2021 at 7:22AM.
Now, let’s explore four different methods of the LocalDateTime class:
import java.time.LocalDateTime;
public class DateTime {
public static void main(String[] args)
{
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.minusDays(60));
System.out.println(ldt.plusMonths(4));
System.out.println(ldt.withDayOfYear(60));
System.out.println(ldt.getDayOfMonth());
}
}
2021-09-21T07:29:56.515749900
2022-03-20T07:29:56.515749900
2021-03-01T07:29:56.515749900
20
Let’s explore each of the methods and their corresponding outputs:
- The first output-
2021-09-21T07:29:56.515749900-was generated through theLocalDateTimeclass’s.minusDays()method, which in this example takes in an integer as a parameter and subtracts that amount of days from the current date-time. In this case, 60 days subtracted from the current date-time equals September 21, 2021 at 7:29AM. - The second output-
2022-03-20T07:29:56.515749900-was generated through theLocalDateTimeclass’s.plusMonths()method. Like the.minusDays()method, this method takes in an integer parameter; however, this method will add a certain number of months to the current date-time. In this case, 4 months added to the current date-time equals March 20, 2022 at 7:29AM. - The third output-
2021-03-01T07:29:56.515749900-was generated through the.withDayOfYear()method. This is one of theLocalDateTimeclass’s more interesting methods since it oftentimes returns a different date from the date in the date-time object. This method, like the previous two I discussed, takes in an integer as a parameter; in this case, the method will return the date corresponding to the Xth day of the year. Since I passed 60 as the integer parameter, this method will return the date March 1, 2021 (the time part of the date-time object remains unchanged). Had I wrote and ran this code last year, this method would’ve returned February 29, 2020, as February 29 is the 60th day of the year in leap years. - The last output-
20-was generated through the.getDayOfMonth()method. In this case, the method simply retrieves the day of the month of the current datetime; since the current date [as of runtime] is November 20, 2021, this method will return 20 since it’s currently the 20th day of the month.
Last but not least, let’s explore the DateTimeFormatter class. This class is different from the previous three classes we discussed because unlike those three classes, this class doesn’t return a datetime object. Rather, this class generates a formatted datetime object from an exisiting datetime object. Let me demonstrate this concept with the code below:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTime {
public static void main(String[] args)
{
LocalDateTime ldt = LocalDateTime.now();
System.out.println("DateTime before formatting: " + ldt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yy HH:mm");
String formattedDateTime = ldt.format(dtf);
System.out.println("DateTime after formatting: " + formattedDateTime);
}
}
DateTime before formatting: 2021-11-28T09:01:48.974227300
DateTime after formatting: 11-28-21 09:01
Ok, so this example looks more complicated than our previous examples. As you can see from the code above, to be able to format a datetime object, we first need to create a datetime object of the LocalDateTime class.
Next, we’d need to create a datetime formatter object using the DateTimeFormatter class. We’d use this class’s .ofPattern() method and pass in a String pattern as the method’s parameter. In this example, I passed the pattern MM-dd-yy HH:mm into the .ofPattern() method; this pattern will display the datetime object with the date portion being displayed month first (followed by the day and year) and the time portion being displayed with just the hour and minute.
- When specifying a datetime pattern to use for the
.ofPattern()method, the month (MM) and hour (HH) will always be written with capital letters. - If you wanted to incorporate the full year into the output (2021 as opposed to just 21), you’ll need to write
yyyyin place ofyy.
Now, as you may have figured out from the code, the datetime formatter will only specify the pattern to use for the datetime object-the formatter (dtf) won’t actually format the DateTime object. Take a look at the line of code with the formattedDateTime object. In order to actually format the LocalDateTime object (ldt), you’ll need to use that object’s .format() method and pass in the object containing the pattern you want to use (dft in this case) as the .format() method’s parameter.
I also included two output lines-one that shows the current datetime before formatting and another one that shows the current datetime after formatting. Since I ran this code at 9:01AM Eastern Standard Time on November 28, 2021, the datetime object after formatting is 11-28-21 09:01.
Thanks for reading,
Michael
