Date and Time in Java

  1. LocalDate represents just a date(year, month, day) — not time.
  2. LocalTime represents only a time(hours, minutes, seconds, nanoseconds).
  3. LocalDateTime represents date and time.

LocalDate

We can use java.time.LocalDate.java to represent a date in our program as an object. In addition, it has many useful methods to manipulate its value.

  • We can add and subtract years, months, days, and weeks from our date object.
  • Note LocalDate is an immutable object so, in order to change it, we need to reassign it and most of the methods return an instance of it.
  • We can get a local date in different string formats by using java.time.format.DateTimeFormatter.java class. The pattern we provide follows regular expression.
  • if our string is in default format (YYYY-MM-dd), we can convert to date object just in one step.
  • if you have your dates in a different format than the default one, you have to use DateTimeFormatter to provide your custom pattern.
  • YYYY pattern doesn’t work so we need to use uuuu for the year.

LocalTime

LocalTime is a class to work with time in java.

  • It’s similar to LocalDate, but it’s used only for a time(hours, minutes, seconds, and nanoseconds).
  • It is immutable as well.
  • LocalTime.now() that’s how we get the current time.

LocalDateTime

The LocalDateTime is used if we need to work with dates and times at the same time.

  • LocalDateTime can work dates and times as well.
  • The methods are really similar to LocalDate and LocalTime
  • After T time goes

Summary

To work with dates only, you can use LocalDate, and to work with time only, you can use LocalTime. LocalDateTime can be used to represent a date and time with one object. You can get the current date & time by using LocalDateTime.now() method. DateTimeFormatter can be used to convert date & time objects to String in different formats. Similarly, it can be used to convert String to date & time objects by providing regular expression patterns.

Q&A

Q: How about time zones? Do local date & time classes handle it automatically?
A: No, they don’t. Java suggests to think we are all in the same time zone, but if you really want to have a time zone option, you will need to use ZonedDateTime class.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store