Tutorial de Java LocalDate(), LocalDateTime(), ZonedDateTime(), Calendar() y Date()
Publicado: 2020-07-18En Java, hemos publicado tutoriales sobre cómo convertir la hora actual en hora de época y cómo calcular la diferencia entre dos instancias de fecha de Java hace algún tiempo.
En este tutorial, repasaremos todas las siguientes API de fecha y calendario de Java:
Fecha Local():
LocalDate es un objeto de fecha y hora inmutable que representa una fecha, a menudo vista como año-mes-día. También se puede acceder a otros campos de fecha, como día del año, día de la semana y semana del año.
FechaHoraLocal():
LocalDateTime es un objeto de fecha y hora inmutable que representa una fecha y hora, a menudo vista como año-mes-día-hora-minuto-segundo.
ZonedDateTime():
ZonedDateTime es una representación inmutable de una fecha y hora con una zona horaria. Esta clase almacena todos los campos de fecha y hora, con una precisión de nanosegundos, y una zona horaria, con un desplazamiento de zona utilizado para manejar fechas y horas locales ambiguas.
Calendario():
La clase Calendario es una clase abstracta que proporciona métodos para convertir entre un instante específico en el tiempo y un conjunto de campos de calendario como AÑO, MES, DÍA_DE_MES, HORA, etc., y para manipular los campos de calendario, como obtener la fecha. de la próxima semana. Un instante en el tiempo se puede representar mediante un valor de milisegundos que es un desplazamiento de la Época, 1 de enero de 1970 00:00:00.000 GMT (gregoriano).
Fecha():
La clase Fecha representa un instante específico en el tiempo, con precisión de milisegundos.
Empecemos:
Crear archivo: CrunchifyDateTimeCalendarTutorial.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
package crunchify.com.tutorials; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * @author Crunchify.com * version: 1.0 * Tutorial: Java LocalDate(), LocalDateTime(), ZonedDateTime(), Calendar() and Date() Tutorial */ public class CrunchifyDateTimeCalendarTutorial { public static void main(String[] args) { // ************************************************ LocalDate ********************************************** // LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as // day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a // LocalDate. crunchifyLog("============ LocalDate test Start ============"); LocalDate currentLocalDate = LocalDate.now(); LocalDate currentLocalNewDate = LocalDate.of(2019, 1, 11); crunchifyLog("LocalDate.now(): " + currentLocalDate); crunchifyLog("LocalDate.of(2019, 1, 11): " + currentLocalNewDate); // Period: A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'. Period period = Period.between(currentLocalDate, currentLocalNewDate); crunchifyLog("Month differences: " + period.getMonths()); if (period.getMonths() <= -3) { crunchifyLog("result: " + currentLocalNewDate + " is older than 3 months!"); } LocalDate currentLocalDateNew = LocalDate.now(); LocalDate threeMonthAgo = LocalDate.now().plusMonths(-3); crunchifyLog("LocalDate.now(): " + currentLocalDateNew); crunchifyLog("LocalDate.now().plusMonths(-3): " + threeMonthAgo); LocalDate crunchifyLocalDate = LocalDate.of(2019, 1, 11); // is this date older than 6 months? if (crunchifyLocalDate.isBefore(threeMonthAgo)) { crunchifyLog("crunchifyLocalDate.isBefore(threeMonthAgo) result: " + crunchifyLocalDate + " is older than 3 months!"); } crunchifyLog("============ LocalDate test End ============ \n"); // ************************************************ LocalDateTime ********************************************** // LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. // Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to // nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime. crunchifyLog("============ LocalDateTime test Start ============"); LocalDateTime currentDate2 = LocalDateTime.now(); LocalDateTime fourMonthAgo = LocalDateTime.now().plusMonths(-4); crunchifyLog("LocalDateTime.now(): " + currentLocalDate); crunchifyLog("LocalDateTime.now().plusMonths(-4): " + fourMonthAgo); LocalDateTime newDate2 = LocalDateTime.of(2019, 7, 1, 0, 0, 0); // Checks if this date-time is before the specified date-time. if (newDate2.isBefore(fourMonthAgo)) { crunchifyLog("isBefore() result: " + newDate2 + " is older than 4 months!"); } long findGap = ChronoUnit.MONTHS.between(currentDate2, newDate2); crunchifyLog(findGap); if (findGap <= -4) { crunchifyLog("findGap result: " + newDate2 + " is older than 4 months!"); } crunchifyLog("============ LocalDateTime test End ============ \n"); // ************************************************ ZonedDateTime ********************************************** // ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a // precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times. For example, the value // "2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris time-zone" can be stored in a ZonedDateTime. crunchifyLog("============ ZonedDateTime test Start ============"); ZonedDateTime crunchifyNow = ZonedDateTime.now(); ZonedDateTime thirtyDaysAgo = crunchifyNow.plusDays(-30); crunchifyLog("ZonedDateTime.now() :" + crunchifyNow); crunchifyLog("now.plusDays(-30) :" + thirtyDaysAgo); ZonedDateTime fiftyDaysAgo = crunchifyNow.plusDays(-50); crunchifyLog("now.plusDays(-50) :" + fiftyDaysAgo); if (fiftyDaysAgo.isBefore(thirtyDaysAgo)) { crunchifyLog("fiftyDaysAgo.isBefore(thirtyDaysAgo): " + thirtyDaysAgo + " is older than 30 days!"); } // ChronoUnit: A standard set of date periods units. // This set of units provide unit-based access to manipulate a date, time or date-time. The standard set of units can be extended by // implementing TemporalUnit. long crunchifyBetween = ChronoUnit.DAYS.between(crunchifyNow, fiftyDaysAgo); crunchifyLog(crunchifyBetween); if (crunchifyBetween < -30) { crunchifyLog("crunchifyBetween < -30 result: " + thirtyDaysAgo + " is older than 30 days!"); } crunchifyLog("============ ZonedDateTime test End ============ \n"); // ************************************************ Calendar ********************************************** // The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of // calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the // date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, // 1970 00:00:00.000 GMT (Gregorian). crunchifyLog("============ Calendar test Start ============"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar fiveMonthsAgo = Calendar.getInstance(); crunchifyLog("Calendar.getInstance(): " + sdf.format(fiveMonthsAgo.getTime())); // Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. fiveMonthsAgo.add(Calendar.MONTH, -5); crunchifyLog("Calendar.MONTH, -5): " + sdf.format(fiveMonthsAgo.getTime())); Calendar crunchifyCalendar = new GregorianCalendar(2019, 7, 11); if (crunchifyCalendar.before(threeMonthAgo)) { crunchifyLog("crunchifyCalendar.before(threeMonthAgo) result : " + sdf.format(crunchifyCalendar.getTime()) + " is older than 5 months"); } crunchifyLog("============ Calendar test End ============ \n"); // ************************************************ Date ********************************************** // Date: The class Date represents a specific instant in time, with millisecond precision. crunchifyLog("============ Date test Start ============"); SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd"); Date crunchifyToday = new Date(); crunchifyLog("new Date(): " + sdf5.format(crunchifyToday)); Calendar twentyDaysAgo = Calendar.getInstance(); twentyDaysAgo.add(Calendar.DAY_OF_MONTH, -20); Date thirtyDaysAgoDate = twentyDaysAgo.getTime(); crunchifyLog("twentyDaysAgo.getTime(): " + sdf5.format(thirtyDaysAgoDate)); Date crunchifyNewDate = null; try { // Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string. crunchifyNewDate = sdf5.parse("2019-07-11"); } catch (ParseException e) { e.printStackTrace(); } if (crunchifyNewDate.before(thirtyDaysAgoDate)) { crunchifyLog(sdf.format(crunchifyNewDate) + " is older than 30 days!"); } crunchifyLog("============ Date test End ============ \n"); } private static void crunchifyLog(Object crunchifyString) { System.out.println(crunchifyString); } } |

Simplemente ejecútelo en IntelliJ IDEA:
Salida de consola.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/ Library / Java / JavaVirtualMachines / jdk - 13.0.1.jdk / Contents / Home / bin / java - javaagent : / Applications / IntelliJ IDEA . app / Contents / lib / idea_rt . jar = 50895 : / Applications / IntelliJ IDEA . app / Contents / bin - Dfile . encoding = UTF - 8 - classpath / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / target / classes : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / zxing - 2.1.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - logging - 1.1.2.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - collections - 3.2.1.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / javax . mail . jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - io - 2.4.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - lang - 2.6.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - configuration - 1.9.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / log4j - 1.2.17.jar : / Users / crunchify / Documents / C / crunchify - github / CrunchifyTutorials / WebContent / WEB - INF / lib / commons - beanutils - 1.8.3.jar : / Users / crunchify / . m2 / repository / org / glassfish / javax . json / 1.0.4 / javax . json - 1.0.4.jar : / Users / crunchify / . m2 / repository / com / github / wnameless / json - flattener / 0.2.2 / json - flattener - 0.2.2.jar : / Users / crunchify / . m2 / repository / com / eclipsesource / minimal - json / minimal - json / 0.9.4 / minimal - json - 0.9.4.jar : / Users / crunchify / . m2 / repository / org / apache / commons / commons - lang3 / 3.4 / commons - lang3 - 3.4.jar : / Users / crunchify / . m2 / repository / com / google / code / gson / gson / 2.8.0 / gson - 2.8.0.jar : / Users / crunchify / . m2 / repository / net / jodah / expiringmap / 0.5.7 / expiringmap - 0.5.7.jar : / Users / crunchify / . m2 / repository / org / apache / httpcomponents / httpclient / 4.3.6 / httpclient - 4.3.6.jar : / Users / crunchify / . m2 / repository / org / apache / httpcomponents / httpcore / 4.3.3 / httpcore - 4.3.3.jar : / Users / crunchify / . m2 / repository / commons - codec / commons - codec / 1.6 / commons - codec - 1.6.jar : / Users / crunchify / . m2 / repository / org / json / json / 20151123 / json - 20151123.jar : / Users / crunchify / . m2 / repository / net / spy / spymemcached / 2.12.3 / spymemcached - 2.12.3.jar : / Users / crunchify / . m2 / repository / com / whalin / Memcached - Java - Client / 3.0.2 / Memcached - Java - Client - 3.0.2.jar : / Users / crunchify / . m2 / repository / commons - pool / commons - pool / 1.5.6 / commons - pool - 1.5.6.jar : / Users / crunchify / . m2 / repository / org / slf4j / slf4j - api / 1.6.4 / slf4j - api - 1.6.4.jar : / Users / crunchify / . m2 / repository / com / googlecode / xmemcached / xmemcached / 2.4.5 / xmemcached - 2.4.5.jar : / Users / crunchify / . m2 / repository / com / paypal / sdk / rest - api - sdk / 1.14.0 / rest - api - sdk - 1.14.0.jar : / Users / crunchify / . m2 / repository / commons - dbcp / commons - dbcp / 20030825.184428 / commons - dbcp - 20030825.184428.jar : / Users / crunchify / . m2 / repository / javax / ws / rs / javax . ws . rs - api / 2.0 / javax . ws . rs - api - 2.0.jar : / Users / crunchify / . m2 / repository / org / hamcrest / hamcrest - all / 1.3 / hamcrest - all - 1.3.jar : / Users / crunchify / . m2 / repository / log4j / log4j / 1.2.17 / log4j - 1.2.17.jar : / Users / crunchify / . m2 / repository / com / google / guava / guava / 19.0 / guava - 19.0.jar : / Users / crunchify / . m2 / repository / com / googlecode / json - simple / json - simple / 1.1 / json - simple - 1.1.jar : / Users / crunchify / . m2 / repository / commons - net / commons - net / 2.0 / commons - net - 2.0.jar : / Users / crunchify / . m2 / repository / asm / asm / 3.3.1 / asm - 3.3.1.jar : / Users / crunchify / . m2 / repository / axis / axis / 1.4 / axis - 1.4.jar : / Users / crunchify / . m2 / repository / org / apache / axis / axis - jaxrpc / 1.4 / axis - jaxrpc - 1.4.jar : / Users / crunchify / . m2 / repository / axis / axis - wsdl4j / 1.5.1 / axis - wsdl4j - 1.5.1.jar : / Users / crunchify / . m2 / repository / commons - beanutils / commons - beanutils / 1.8.3 / commons - beanutils - 1.8.3.jar : / Users / crunchify / . m2 / repository / commons - collections / commons - collections / 3.2.1 / commons - collections - 3.2.1.jar : / Users / crunchify / . m2 / repository / commons - configuration / commons - configuration / 1.10 / commons - configuration - 1.10.jar : / Users / crunchify / . m2 / repository / commons - io / commons - io / 2.4 / commons - io - 2.4.jar : / Users / crunchify / . m2 / repository / commons - discovery / commons - discovery / 0.5 / commons - discovery - 0.5.jar : / Users / crunchify / . m2 / repository / commons - lang / commons - lang / 2.6 / commons - lang - 2.6.jar : / Users / crunchify / . m2 / repository / commons - logging / commons - logging / 1.1.3 / commons - logging - 1.1.3.jar : / Users / crunchify / . m2 / repository / commons - logging / commons - logging - api / 1.1 / commons - logging - api - 1.1.jar : / Users / crunchify / . m2 / repository / javax / mail / mail / 1.4.7 / mail - 1.4.7.jar : / Users / crunchify / . m2 / repository / javax / activation / activation / 1.1 / activation - 1.1.jar : / Users / crunchify / . m2 / repository / javax / xml / jaxrpc - api / 1.1 / jaxrpc - api - 1.1.jar : / Users / crunchify / . m2 / repository / javax / servlet / javax . servlet - api / 3.1.0 / javax . servlet - api - 3.1.0.jar : / Users / crunchify / . m2 / repository / org / apache / axis / axis - saaj / 1.4 / axis - saaj - 1.4.jar : / Users / crunchify / . m2 / repository / wsdl4j / wsdl4j / 1.6.3 / wsdl4j - 1.6.3.jar : / Users / crunchify / . m2 / repository / com / google / zxing / core / 3.2.1 / core - 3.2.1.jar : / Users / crunchify / . m2 / repository / org / apache / commons / commons - compress / 1.9 / commons - compress - 1.9.jar : / Users / crunchify / . m2 / repository / mysql / mysql - connector - java / 5.1.6 / mysql - connector - java - 5.1.6.jar : / Users / crunchify / . m2 / repository / junit / junit / 4.12 / junit - 4.12.jar : / Users / crunchify / . m2 / repository / org / hamcrest / hamcrest - core / 1.3 / hamcrest - core - 1.3.jar : / Users / crunchify / . m2 / repository / ch / qos / logback / logback - classic / 1.2.3 / logback - classic - 1.2.3.jar : / Users / crunchify / . m2 / repository / ch / qos / logback / logback - core / 1.2.3 / logback - core - 1.2.3.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - context / 5.1.3.RELEASE / spring - context - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - aop / 5.1.3.RELEASE / spring - aop - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - beans / 5.1.3.RELEASE / spring - beans - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - core / 5.1.3.RELEASE / spring - core - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - jcl / 5.1.3.RELEASE / spring - jcl - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - expression / 5.1.3.RELEASE / spring - expression - 5.1.3.RELEASE.jar : / Users / crunchify / . m2 / repository / org / springframework / spring - context - support / 5.1.3.RELEASE / spring - context - support - 5.1.3.RELEASE.jar crunchify . com . tutorials . CrunchifyDateTimeCalendarTutorial ============ LocalDate test Start ============ LocalDate . now ( ) : 2020 - 07 - 18 LocalDate . of ( 2019 , 1 , 11 ) : 2019 - 01 - 11 Month differences : - 6 result : 2019 - 01 - 11 is older than 3 months ! LocalDate . now ( ) : 2020 - 07 - 18 LocalDate . now ( ) . plusMonths ( - 3 ) : 2020 - 04 - 18 crunchifyLocalDate . isBefore ( threeMonthAgo ) result : 2019 - 01 - 11 is older than 3 months ! ============ LocalDate test End ============ ============ LocalDateTime test Start ============ LocalDateTime . now ( ) : 2020 - 07 - 18 LocalDateTime . now ( ) . plusMonths ( - 4 ) : 2020 - 03 - 18T10 : 27 : 28.285711 isBefore ( ) result : 2019 - 07 - 01T00 : 00 is older than 4 months ! - 12 findGap result : 2019 - 07 - 01T00 : 00 is older than 4 months ! ============ LocalDateTime test End ============ ============ ZonedDateTime test Start ============ ZonedDateTime . now ( ) : 2020 - 07 - 18T10 : 27 : 28.286147 - 05 : 00 [ America / Chicago ] now . plusDays ( - 30 ) : 2020 - 06 - 18T10 : 27 : 28.286147 - 05 : 00 [ America / Chicago ] now . plusDays ( - 50 ) : 2020 - 05 - 29T10 : 27 : 28.286147 - 05 : 00 [ America / Chicago ] fiftyDaysAgo . isBefore ( thirtyDaysAgo ) : 2020 - 06 - 18T10 : 27 : 28.286147 - 05 : 00 [ America / Chicago ] is older than 30 days ! - 50 crunchifyBetween < - 30 result : 2020 - 06 - 18T10 : 27 : 28.286147 - 05 : 00 [ America / Chicago ] is older than 30 days ! ============ ZonedDateTime test End ============ ============ Calendar test Start ============ Calendar . getInstance ( ) : 2020 - 07 - 18 Calendar . MONTH , - 5 ) : 2020 - 02 - 18 ============ Calendar test End ============ ============ Date test Start ============ new Date ( ) : 2020 - 07 - 18 twentyDaysAgo . getTime ( ) : 2020 - 06 - 28 2019 - 07 - 11 is older than 30 days ! ============ Date test End ============ Process finished with exit code 0 |
Espero que este tutorial lo ayude a utilizar todas estas API de fecha y hora.