{"id":3254,"date":"2025-10-06T16:09:25","date_gmt":"2025-10-06T14:09:25","guid":{"rendered":"https:\/\/tecnologia.euroinnova.com\/las-fechas-en-java-todo-lo-que-debes-saber-sobre-las-variables-tipo-date\/"},"modified":"2026-08-05T11:05:47","modified_gmt":"2026-08-05T09:05:47","slug":"date-java","status":"publish","type":"post","link":"https:\/\/tecnologia.euroinnova.com\/en\/date-java","title":{"rendered":"Dates in Java: everything you need to know about date variables"},"content":{"rendered":"<p><strong>Java<\/strong> is a <strong>programming language<\/strong> which has evolved and improved over time. One example of this is the lessons on working with dates <strong>java.util.Date<\/strong> y <strong>java.util.Calendar<\/strong>, 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 <strong>date type.<\/strong><\/p>\n<p>The <strong>java.time package<\/strong> It is a good option for handling dates in Java, although it has certain peculiarities and variables that you need to bear in mind. <strong>Have you heard of LocalTime or LocalDateTime?<\/strong> Get ready, because we\u2019re going to explore this topic in depth, so that by the end of this article you\u2019ll have all the information you need. If, even then, you still want to learn more about Java, we recommend the <a href=\"https:\/\/www.euroinnova.com\/diplomado-programacion-udavinci-mx\" target=\"_blank\" rel=\"noopener\">Advanced Course in Front-end Programming with JavaScript and Angular.<\/a><\/p>\n<h2 id=\"que-es-date-en-java\"><strong>What is `date` in Java?<\/strong><\/h2>\n<p>The <strong>date management<\/strong> 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 <strong>Date class<\/strong> It has been part of Java since the earliest versions of the language, allowing a point in time to be represented <strong>(milliseconds since 1 January 1970, 00:00:00 GMT).<\/strong><\/p>\n<p>Even so, the most recent versions of Java have replaced the Date class with the classes in the <strong>java.time.<\/strong> 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 <strong>Java 8,<\/strong> as <strong>LocalDate<\/strong>, <strong>LocalTime<\/strong> y <strong>LocalDateTime<\/strong>, which provide greater precision and control over date-related operations.<\/p>\n<h2 id=\"como-sacar-la-fecha-en-java\"><strong>How do you extract the date in Java?<\/strong><\/h2>\n<p>Retrieving the current date in Java is a straightforward process, as we simply need to use the class <strong>LocalDate<\/strong> of the parcel <strong>java.time.<\/strong> This method allows you to retrieve the system\u2019s current date efficiently. Here is an example of how to do it:<\/p>\n<p><em>import java.time.LocalDate;<\/em><\/p>\n<p><em>public class DateExample { <\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>LocalDate today = LocalDate.now(); <\/em><\/p>\n<p><em>System.out.println(\u00abToday\u2019s Date: \u00bb + today);<\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>\n<p>As we can see in this code, there is a `now()` method in the class <strong>LocalDate.<\/strong> This returns the current date in the format <strong>yyyy-mm-dd<\/strong>, which is the standard format in Java. If we also want to retrieve the time, we will need to use the class <strong>LocalDateTime.<\/strong><\/p>\n<p>As can be seen, this method is more modern than the Date class, as it offers greater flexibility and compatibility with the <strong>date and time formats in Java.<\/strong><\/p>\n<h2 id=\"como-declarar-una-variable-de-tipo-date-en-java\"><strong>How do you declare a variable of type \u2018date\u2019 in Java?<\/strong><\/h2>\n<p>Declare a variable of <strong>Date type<\/strong> In Java, it\u2019s 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 <strong>java.util<\/strong>, which declares a variable of type Date and initialises it with the current date and time.<\/p>\n<p><em>import java.util.Date;<\/em><\/p>\n<p><em>public class DateDeclaration { <\/em><\/p>\n<p><em>public static void main(String[] args) {<\/em><\/p>\n<p><em>\u00a0Date date = new Date(); \/\/ Current date <\/em><\/p>\n<p><em>System.out.println(\u00abCurrent date: \u00bb + date);<\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>\n<p>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 <strong>java.time<\/strong>, which offers greater precision and control. It would look like this with the class <strong>LocalDate.<\/strong><\/p>\n<p><em>import java.time.LocalDate;<\/em><\/p>\n<p><em>public class LocalDateExample { <\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>LocalDate localDate = LocalDate.of(2023, 10, 12); \/\/ Year, month and day <\/em><\/p>\n<p><em>System.out.println(\u00abDate: \u00bb + localDate); <\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>\n<p>The year, month and day values are specified here. Furthermore, the use of <strong>formatting a Java date<\/strong> facilitates the <strong>date parsing<\/strong> and its conversion into different formats.<\/p>\n<h2 id=\"el-paquete-java-time-en-profundidad\"><strong>The java.time package, in depth<\/strong><\/h2>\n<p>Now it\u2019s time to dive straight into the <strong>java.time package<\/strong>. As we have said, it was introduced in <strong>Java 8<\/strong> to improve the handling of dates and times, resolving the <strong>Limitations of the Date and Calendar classes.<\/strong> This package includes classes such as LocalDate, LocalTime, LocalDateTime and ZonedDateTime, each designed for a specific purpose.<\/p>\n<p>The java.time package is based on the <strong>principles of immutability and clarity<\/strong>, 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 <strong>date formatting in Java.<\/strong><\/p>\n<h3 id=\"localdate\"><strong>LocalDate<\/strong><\/h3>\n<p>The <strong>LocalDate class<\/strong> 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 <strong>the now() method.<\/strong><\/p>\n<p>You can also add or subtract days, months or years from a date using methods such as <strong>plusDays() or minusMonths().<\/strong> Furthermore, dates can be compared using methods such as <strong>isBefore() or isAfter().<\/strong> Here\u2019s an example of how to add days to a date:<\/p>\n<p><em>LocalDate today = LocalDate.now(); <\/em><\/p>\n<p><em>LocalDate futureDate = today.plusDays(10); \/\/ Add 10 days <\/em><\/p>\n<p><em>System.out.println(\u00abFuture date: \u00bb + futureDate);<\/em><\/p>\n<p>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.<\/p>\n<h3 id=\"localtime\"><strong>LocalTime<\/strong><\/h3>\n<p><strong>LocalTime<\/strong> is another class in the package <strong>java.time<\/strong> 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,<\/p>\n<p>Here is an example:<\/p>\n<p><em>LocalTime time = LocalTime.of(14, 30); \/\/ Time: 14:30 <\/em><\/p>\n<p><em>System.out.println(\u00abTime: \u00bb + time);<\/em><\/p>\n<h3 id=\"localdatetime\"><strong>LocalDateTime<\/strong><\/h3>\n<p>The class <strong>LocalDateTime<\/strong> 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.<\/p>\n<p>Here is an example of <strong>LocalDateTime<\/strong> using the method <strong>of()<\/strong> to set both the date and the time.<\/p>\n<p><em>LocalDateTime dateTime = LocalDateTime.of(2023, 10, 12, 14, 30); \/\/ Year, month, day, hour and minute <\/em><\/p>\n<p><em>System.out.println(\u00abDate and time: \u00bb + dateTime);<\/em><\/p>\n<h3 id=\"instant\"><strong>Instant<\/strong><\/h3>\n<p><strong>Instant<\/strong> is a Java class for representing a specific point in time on the timeline, measured in nanoseconds from the <strong>1 January 1970, 00:00:00 GMT.<\/strong> The difference is that we work with a <strong>universal concept of time (UTC)<\/strong>, ideal for operations where a very high degree of temporal precision is required.<\/p>\n<p>Here\u2019s a quick example:<\/p>\n<p><em>Instant instant = Instant.now(); \/\/ Current date and time in UTC format <\/em><\/p>\n<p><em>System.out.println(\u00abInstant: \u00bb + instant);<\/em><\/p>\n<h3 id=\"zoneddatetime\"><strong>ZonedDateTime<\/strong><\/h3>\n<p>The class <strong>ZonedDateTime<\/strong> 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.<\/p>\n<p>Here is an example of how to create a ZonedDateTime:<\/p>\n<p><em>ZonedDateTime zonedDateTime = ZonedDateTime.now(); <\/em><\/p>\n<p><em>System.out.println(\u00abDate and time with time zone: \u00bb + zonedDateTime);<\/em><\/p>\n<h3 id=\"period\"><strong>Period<\/strong><\/h3>\n<p><strong>Period<\/strong> is another important class in Java for representing a time interval in terms of <strong>years, months and days.<\/strong> 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 <strong>between().<\/strong><\/p>\n<p><em>LocalDate startDate = LocalDate.of(2020, 1, 1); <\/em><\/p>\n<p><em>LocalDate endDate = LocalDate.now(); <\/em><\/p>\n<p><em>Period period = Period.between(startDate, endDate); <\/em><\/p>\n<p><em>System.out.println(\u00abDifference: \u00bb + period.getYears() + \u00bb years\u00bb);<\/em><\/p>\n<h3 id=\"duration\"><strong>Duration<\/strong><\/h3>\n<p><strong>Duration<\/strong> It is designed to represent a time interval, but in terms of <strong>hours, minutes, seconds and nanoseconds.<\/strong> The difference between it and Period is that it is designed to measure shorter, more specific periods of time, such as a telephone call.<\/p>\n<p>Here\u2019s how to create a Duration:<\/p>\n<p><em>LocalTime startTime = LocalTime.of(10, 0); <\/em><\/p>\n<p><em>LocalTime endTime = LocalTime.of(12, 30); <\/em><\/p>\n<p><em>Duration duration = Duration.between(startTime, endTime); <\/em><\/p>\n<p><em>System.out.println(\u00abDuration: \u00bb + duration.toHours() + \u00bb hours\u00bb);<\/em><\/p>\n<h2 id=\"partes-de-una-fecha-o-una-hora\"><strong>Parts of a date or time<\/strong><\/h2>\n<p>In Java, a <strong>date or time<\/strong> consists of several parts. For example, in the lesson <strong>LocalDate<\/strong>, you can extract the year, month and day from a specific date using methods such as <strong>getYear(), getMonthValue and getDayofMonth().<\/strong> Here is an example:<\/p>\n<p><em>LocalDate date = LocalDate.now(); <\/em><\/p>\n<p><em>int year = date.getYear(); <\/em><\/p>\n<p><em>int month = date.getMonthValue(); <\/em><\/p>\n<p><em>int day = date.getDayOfMonth(); <\/em><\/p>\n<p><em>System.out.println(\u00abYear: \u00bb + year + \u00ab, Month: \u00bb + month + \u00ab, Day: \u00bb + day);<\/em><\/p>\n<p>The same can be done with the components of an hour, such as hours, minutes and seconds. In this case, methods such as <strong>getHour(), getMinute() and getSecond().<\/strong><\/p>\n<p><em>LocalTime time = LocalTime.now(); <\/em><\/p>\n<p><em>int hour = time.getHour(); <\/em><\/p>\n<p><em>int minute = time.getMinute();\u00a0<\/em><\/p>\n<p><em>System.out.println(\u00abHour: \u00bb + hour + \u00ab, Minute: \u00bb + minute);<\/em><\/p>\n<h2 id=\"transformar-fechas-y-horas\"><strong>Converting dates and times<\/strong><\/h2>\n<p>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 <strong>LocalDate, LocalTime, LocalDateTime and ZonedDateTime.<\/strong><\/p>\n<p>For example, to convert a LocalDate object to a LocalDateTime, you can simply combine a date with a time using the method <strong>atTime().<\/strong><\/p>\n<p><em>LocalDate date = LocalDate.now(); <\/em><\/p>\n<p><em>LocalDateTime dateTime = date.atTime(14, 30); <\/em><\/p>\n<p><em>System.out.println(\u00abDate and time: \u00bb + dateTime);<\/em><\/p>\n<p>Similarly, for <strong>convert a date<\/strong> 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.<\/p>\n<p><em>DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\u00abdd-MM-yyyy\u00bb); <\/em><\/p>\n<p><em>String formattedDate = date.format(formatter); <\/em><\/p>\n<p><em>System.out.println(\u00abFormatted date: \u00bb + formattedDate);<\/em><\/p>\n<h2 id=\"ajustes-temporales\"><strong>Temporary adjustments<\/strong><\/h2>\n<p>The <strong>temporary adjustments<\/strong> 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 <strong>withDayOfMonth().<\/strong><\/p>\n<p><em>LocalDate endOfMonth = today.withDayOfMonth(today.lengthOfMonth()); <\/em><\/p>\n<p><em>System.out.println(\u00abLast day of the month: \u00bb + endOfMonth);<\/em><\/p>\n<h2 id=\"formato-personalizado-de-fechas\"><strong>Custom date format<\/strong><\/h2>\n<p>The date format can also be customised in Java using the class <strong>DateTimeFormatter,<\/strong> which allows you to define specific formats for converting times and dates. For example, if you want to format a date in the format <strong>dd-mm-yyyy,<\/strong> You can use the following code:<\/p>\n<p><em>DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\u00abdd-MM-yyyy\u00bb); <\/em><\/p>\n<p><em>LocalDate date = LocalDate.now(); <\/em><\/p>\n<p><em>String formattedDate = date.format(formatter); <\/em><\/p>\n<p><em>System.out.println(\u00abDate in custom format: \u00bb + formattedDate);<\/em><\/p>\n<p>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\u2019t forget to <strong>DateTimeFormatter.<\/strong><\/p>\n<h2 id=\"ejemplos-practicos\"><strong>Practical examples<\/strong><\/h2>\n<p>To round off this post, we can\u2019t think of a better way than to give you a few practical examples of how to use the classes and methods of the <strong>java.time. package.<\/strong><\/p>\n<h3 id=\"obtener-la-fecha-y-hora-actuales\"><strong>Get the current date and time<\/strong><\/h3>\n<p>This is a simple example of how to retrieve the current date and time using <strong>LocalDateTime:<\/strong><\/p>\n<p><em>import java.time.LocalDateTime;<\/em><\/p>\n<p><em>public class DateTimeExample { <\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>LocalDateTime currentDateTime = LocalDateTime.now(); <\/em><\/p>\n<p><em>System.out.println(\u00abCurrent date and time: \u00bb + currentDateTime); <\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>\n<h3 id=\"formatear-una-fecha\"><strong>Formatting a date<\/strong><\/h3>\n<p>Below, we show you how to format a date using <strong>DateTimeFormatter:<\/strong><\/p>\n<p><em>import java.time.LocalDate; <\/em><\/p>\n<p><em>import java.time.format.DateTimeFormatter;<\/em><\/p>\n<p><em>public class FormatDateExample { <\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>LocalDate date = LocalDate.now(); <\/em><\/p>\n<p><em>DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\u00abdd-MM-yyyy\u00bb);\u00a0<\/em><\/p>\n<p><em>String formattedDate = date.format(formatter); <\/em><\/p>\n<p><em>System.out.println(\u00abFormatted date: \u00bb + formattedDate); } }<\/em><\/p>\n<h3 id=\"calcular-la-diferencia-entre-dos-fechas\"><strong>Calculate the difference between two dates<\/strong><\/h3>\n<p>Here, we use <strong>Period<\/strong> to calculate the difference in years, months and days between two different dates:<\/p>\n<p><em>import java.time.LocalDate; <\/em><\/p>\n<p><em>import java.time.Period;<\/em><\/p>\n<p><em>public class PeriodExample {\u00a0<\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>LocalDate startDate = LocalDate.of(2020, 1, 1); <\/em><\/p>\n<p><em>LocalDate endDate = LocalDate.now(); <\/em><\/p>\n<p><em>Period period = Period.between(startDate, endDate); <\/em><\/p>\n<p><em>System.out.println(\u00abIt has been \u00bb + period.getYears() + \u00bb years, \u00ab<\/em><\/p>\n<p><em>period.getMonths() + \u00bb months, and \u00bb + period.getDays() + \u00bb days.\u00bb); <\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>\n<h3 id=\"trabajar-con-zonas-horarias\"><strong>Working with time zones<\/strong><\/h3>\n<p>To finish off, here\u2019s an example of how to work with <strong>ZonedDateTime<\/strong> to manage dates and times across different time zones:<\/p>\n<p><em>import java.time.ZonedDateTime; <\/em><\/p>\n<p><em>import java.time.ZoneId;<\/em><\/p>\n<p><em>public class ZonedDateTimeExample { <\/em><\/p>\n<p><em>public static void main(String[] args) { <\/em><\/p>\n<p><em>ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(\u00abAmerica\/New_York\u00bb)); <\/em><\/p>\n<p><em>System.out.println(\u00abDate and time in New York: \u00bb + zonedDateTime);<\/em><\/p>\n<p><em>} <\/em><\/p>\n<p><em>}<\/em><\/p>","protected":false},"excerpt":{"rendered":"<p>Java es un lenguaje de programaci\u00f3n que ha ido avanzando y mejorando con el tiempo. Un ejemplo de ello son [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":861,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3254","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sin-categorizar"],"acf":[],"_links":{"self":[{"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/posts\/3254","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/comments?post=3254"}],"version-history":[{"count":0,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/posts\/3254\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/media\/861"}],"wp:attachment":[{"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/media?parent=3254"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/categories?post=3254"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tecnologia.euroinnova.com\/en\/wp-json\/wp\/v2\/tags?post=3254"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}