Dates in Java: everything you need to know about date variables

Table of contents

Summarise with:

Java is a programming language which has evolved and improved over time. One example of this is the lessons on working with dates java.util.Date y java.util.Calendar, which have existed since the dawn of time. However, these classes are not the most suitable for handling dates in Java. For this reason, at Euroinnova we are going to focus on the variables of the date type.

The java.time package It is a good option for handling dates in Java, although it has certain peculiarities and variables that you need to bear in mind. Have you heard of LocalTime or LocalDateTime? Get ready, because we’re going to explore this topic in depth, so that by the end of this article you’ll have all the information you need. If, even then, you still want to learn more about Java, we recommend the Advanced Course in Front-end Programming with JavaScript and Angular.

What is `date` in Java?

The date management In Java, this is of great importance for many applications, as it is the only way to record and manage chronological events. As we have said, the Date class It has been part of Java since the earliest versions of the language, allowing a point in time to be represented (milliseconds since 1 January 1970, 00:00:00 GMT).

Even so, the most recent versions of Java have replaced the Date class with the classes in the java.time. Why? Because its functionality was limited by certain inconsistencies, such as the lack of direct support for time zones. Consequently, new classes were introduced in Java 8, as LocalDate, LocalTime y LocalDateTime, which provide greater precision and control over date-related operations.

How do you extract the date in Java?

Retrieving the current date in Java is a straightforward process, as we simply need to use the class LocalDate of the parcel java.time. This method allows you to retrieve the system’s current date efficiently. Here is an example of how to do it:

import java.time.LocalDate;

public class DateExample {

public static void main(String[] args) {

LocalDate today = LocalDate.now();

System.out.println(«Today’s Date: » + today);

}

}

As we can see in this code, there is a `now()` method in the class LocalDate. This returns the current date in the format yyyy-mm-dd, which is the standard format in Java. If we also want to retrieve the time, we will need to use the class LocalDateTime.

As can be seen, this method is more modern than the Date class, as it offers greater flexibility and compatibility with the date and time formats in Java.

How do you declare a variable of type ‘date’ in Java?

Declare a variable of Date type In Java, it’s very simple, but you do need to know which type of date you need to use in your project. For example, in this project, the java.util, which declares a variable of type Date and initialises it with the current date and time.

import java.util.Date;

public class DateDeclaration {

public static void main(String[] args) {

 Date date = new Date(); // Current date

System.out.println(«Current date: » + date);

}

}

The value represented by this date will be printed as a string, including the hour and minute. However, we already know that the Date class has certain limitations, so we recommend using the new classes from the package java.time, which offers greater precision and control. It would look like this with the class LocalDate.

import java.time.LocalDate;

public class LocalDateExample {

public static void main(String[] args) {

LocalDate localDate = LocalDate.of(2023, 10, 12); // Year, month and day

System.out.println(«Date: » + localDate);

}

}

The year, month and day values are specified here. Furthermore, the use of formatting a Java date facilitates the date parsing and its conversion into different formats.

The java.time package, in depth

Now it’s time to dive straight into the java.time package. As we have said, it was introduced in Java 8 to improve the handling of dates and times, resolving the Limitations of the Date and Calendar classes. This package includes classes such as LocalDate, LocalTime, LocalDateTime and ZonedDateTime, each designed for a specific purpose.

The java.time package is based on the principles of immutability and clarity, enabling more precise and secure handling of dates and times in Java applications. Furthermore, its format makes it more intuitive and modern to use, making it easier to read, write and convert dates in various date formatting in Java.

LocalDate

The LocalDate class It is the main tool in java.time, as it allows you to work with dates without having to manage time zones or specific times. This class is very useful for storing events that only require date information; furthermore, you can retrieve the current date using the the now() method.

You can also add or subtract days, months or years from a date using methods such as plusDays() or minusMonths(). Furthermore, dates can be compared using methods such as isBefore() or isAfter(). Here’s an example of how to add days to a date:

LocalDate today = LocalDate.now();

LocalDate futureDate = today.plusDays(10); // Add 10 days

System.out.println(«Future date: » + futureDate);

In this way, you can manipulate deadlines or events scheduled for specific dates without having to use time components such as hour, minute or hh mm ss.

LocalTime

LocalTime is another class in the package java.time which allows you to manage time without linking it to a specific date, as it only contains information on hours, minutes, seconds and nanoseconds. It is therefore ideal for situations where you simply need to record times without worrying about the day, such as opening hours,

Here is an example:

LocalTime time = LocalTime.of(14, 30); // Time: 14:30

System.out.println(«Time: » + time);

LocalDateTime

The class LocalDateTime It combines both the date and the time into a single object, making it one of the most versatile classes in java.time. Why? Because it includes the functionality of both LocalDate and LocalTime, handling both the date and the time without taking the time zone into account.

Here is an example of LocalDateTime using the method of() to set both the date and the time.

LocalDateTime dateTime = LocalDateTime.of(2023, 10, 12, 14, 30); // Year, month, day, hour and minute

System.out.println(«Date and time: » + dateTime);

Instant

Instant is a Java class for representing a specific point in time on the timeline, measured in nanoseconds from the 1 January 1970, 00:00:00 GMT. The difference is that we work with a universal concept of time (UTC), ideal for operations where a very high degree of temporal precision is required.

Here’s a quick example:

Instant instant = Instant.now(); // Current date and time in UTC format

System.out.println(«Instant: » + instant);

ZonedDateTime

The class ZonedDateTime It combines the functionality of LocalDateTime with time zone handling, allowing us to work with dates and times in different locations. In international applications, events take place in different time zones, so automatic conversions are required.

Here is an example of how to create a ZonedDateTime:

ZonedDateTime zonedDateTime = ZonedDateTime.now();

System.out.println(«Date and time with time zone: » + zonedDateTime);

Period

Period is another important class in Java for representing a time interval in terms of years, months and days. Above all, it is used when you want to calculate the difference between two dates without taking hours or seconds into account. A Period can therefore be created very easily using the method between().

LocalDate startDate = LocalDate.of(2020, 1, 1);

LocalDate endDate = LocalDate.now();

Period period = Period.between(startDate, endDate);

System.out.println(«Difference: » + period.getYears() + » years»);

Duration

Duration It is designed to represent a time interval, but in terms of hours, minutes, seconds and nanoseconds. The difference between it and Period is that it is designed to measure shorter, more specific periods of time, such as a telephone call.

Here’s how to create a Duration:

LocalTime startTime = LocalTime.of(10, 0);

LocalTime endTime = LocalTime.of(12, 30);

Duration duration = Duration.between(startTime, endTime);

System.out.println(«Duration: » + duration.toHours() + » hours»);

Parts of a date or time

In Java, a date or time consists of several parts. For example, in the lesson LocalDate, you can extract the year, month and day from a specific date using methods such as getYear(), getMonthValue and getDayofMonth(). Here is an example:

LocalDate date = LocalDate.now();

int year = date.getYear();

int month = date.getMonthValue();

int day = date.getDayOfMonth();

System.out.println(«Year: » + year + «, Month: » + month + «, Day: » + day);

The same can be done with the components of an hour, such as hours, minutes and seconds. In this case, methods such as getHour(), getMinute() and getSecond().

LocalTime time = LocalTime.now();

int hour = time.getHour();

int minute = time.getMinute(); 

System.out.println(«Hour: » + hour + «, Minute: » + minute);

Converting dates and times

This is a common question, as converting dates and times in Java is one of the most common tasks. However, it is actually very easy to do this when using classes such as LocalDate, LocalTime, LocalDateTime and ZonedDateTime.

For example, to convert a LocalDate object to a LocalDateTime, you can simply combine a date with a time using the method atTime().

LocalDate date = LocalDate.now();

LocalDateTime dateTime = date.atTime(14, 30);

System.out.println(«Date and time: » + dateTime);

Similarly, for convert a date To format a date or time to a specific string format, you can use DateTimeFormatter, which allows you to define the desired format and then apply it to the date or time.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(«dd-MM-yyyy»);

String formattedDate = date.format(formatter);

System.out.println(«Formatted date: » + formattedDate);

Temporary adjustments

The temporary adjustments are used in Java to modify dates or times in accordance with certain predefined rules. As we have already seen, days, weeks, months or years can be added or subtracted using a set of methods. However, adjustments can also be made based on specific days of the month or year. For example, adjusting a date so that it falls on the last day of the month using the method withDayOfMonth().

LocalDate endOfMonth = today.withDayOfMonth(today.lengthOfMonth());

System.out.println(«Last day of the month: » + endOfMonth);

Custom date format

The date format can also be customised in Java using the class DateTimeFormatter, which allows you to define specific formats for converting times and dates. For example, if you want to format a date in the format dd-mm-yyyy, You can use the following code:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(«dd-MM-yyyy»);

LocalDate date = LocalDate.now();

String formattedDate = date.format(formatter);

System.out.println(«Date in custom format: » + formattedDate);

There are projects where dates need to be displayed in a specific way, such as in reports or in applications where users are based in different regions with different date formats. Therefore, you mustn’t forget to DateTimeFormatter.

Practical examples

To round off this post, we can’t think of a better way than to give you a few practical examples of how to use the classes and methods of the java.time. package.

Get the current date and time

This is a simple example of how to retrieve the current date and time using LocalDateTime:

import java.time.LocalDateTime;

public class DateTimeExample {

public static void main(String[] args) {

LocalDateTime currentDateTime = LocalDateTime.now();

System.out.println(«Current date and time: » + currentDateTime);

}

}

Formatting a date

Below, we show you how to format a date using DateTimeFormatter:

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

public class FormatDateExample {

public static void main(String[] args) {

LocalDate date = LocalDate.now();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(«dd-MM-yyyy»); 

String formattedDate = date.format(formatter);

System.out.println(«Formatted date: » + formattedDate); } }

Calculate the difference between two dates

Here, we use Period to calculate the difference in years, months and days between two different dates:

import java.time.LocalDate;

import java.time.Period;

public class PeriodExample { 

public static void main(String[] args) {

LocalDate startDate = LocalDate.of(2020, 1, 1);

LocalDate endDate = LocalDate.now();

Period period = Period.between(startDate, endDate);

System.out.println(«It has been » + period.getYears() + » years, «

period.getMonths() + » months, and » + period.getDays() + » days.»);

}

}

Working with time zones

To finish off, here’s an example of how to work with ZonedDateTime to manage dates and times across different time zones:

import java.time.ZonedDateTime;

import java.time.ZoneId;

public class ZonedDateTimeExample {

public static void main(String[] args) {

ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(«America/New_York»));

System.out.println(«Date and time in New York: » + zonedDateTime);

}

}

Share in:

Related articles

ITIL principles and best practices

ITIL, or Information Technology Infrastructure Library, is a set of practices and frameworks for Information Technology Service Management (ITSM). They were developed by the UK Government's Central Computing and Telecoms Agency (OGC) in the

Hash

A hash is a mathematical function that takes an input (such as a file, a message, or any type of data) and returns a fixed-length alphanumeric string of characters that uniquely represents that input. Simply put, it is like

Insight

By insight we mean a deep and clear understanding of a situation, behaviour or problem that is not immediately obvious and that may reveal significant patterns, trends or relationships of interest. They are critical as they allow us to make more strategic decisions when making decisions.

MLOps

MLOps, or Machine Learning Operations, is a practice that unites the principles of software development (DevOps) with the specific requirements of machine learning (ML) systems. Its purpose is to optimise and automate the entire lifecycle of

Scroll to Top