Localdatetime java 8 example

Полное руководство по Java 8 Date Time API. Примеры LocalDate, Instant, LocalDateTime, Parse и Format

Полное руководство по Java 8 Date Time API. Примеры LocalDate, Instant, LocalDateTime, Parse и Format

С самых первых версий в Java не было единого и удобного подхода для работы с датой и временем, поэтому новый Date/Time API является одним из самых нужных и важных нововведений в Java 8. В этой статье мы на примерах рассмотрим все самые главные нововведения для работы с датой и временем.

Что нам дает новый Java Date Time API?

Прежде чем мы начнем разбираться с новым Java 8 Date Time API, давайте рассмотрим главные проблемы в работе с датой и временем версий Java 7 и ниже:

  1. Классы Java Date Time раскиданы по пакетам. Так, класс Date Class есть как в пакете java.util , так и в java.sql пакете. Классы для форматирования и парсинга определены в java.text пакете.
  2. Пакет java.util.Date содержит как дату, так и время, в то время как java.sql.Date содержит только дату. По моему, оба класса не очень хорошо спроектированы.
  3. Все классы для работы с датой могут изменяться, поэтому они не потокобезопасны. Это одна из самых больших проблем в Date и Calendar классах.
  4. Класс Date не обеспечивает интернационализацию, не поддерживает часовые пояса. Поэтому были введены классы java.util.Calendar и java.util.TimeZone , но опять-таки, они имеют все перечисленные выше проблемы.
Читайте также:  Css template to wordpress theme

Ввиду всех перечисленных выше недостатков сторонними разработчиками была создана библиотека для работы с датой и временем. Она называется Joda Time и очень часто используется в качестве замены стандартным Java классам. Но это тема уже другой статьи.

Разбор Java 8 Date Time API

Java 8 Date Time API предназначена заменить старые классы для работы со временем и датой. Давайте рассмотрим основные пакеты нового API.

  1. Пакет java.time — Это базовый пакет нового Date Time API. Все основные базовые классы являются частью этого пакета: LocalDate , LocalTime , LocalDateTime , Instant , Period , Duration и другие. Все эти классы являются неизменными и потокобезопасными. В большинстве случаев, этих классов будет достаточно для большинства задач.
  2. Пакет j ava.time.chrono — пакет с общими интерфейсами для не календарных систем ISO. Мы можем наследовать класс AbstractChronology для создания собственной календарной системы.
  3. Пакет java.time.format — пакет с классами форматирования и парсинга времени и даты. В большинстве случаев, мы не будем использовать их напрямую, потому что классы в пакете java.time предоставляют удобные методы для форматирования и парсинга.
  4. Пакет java.time.temporal используется для работы с временными объектами, например, с помощью него мы можем узнать первый или последний день месяца. Методы таких классов сразу заметны на фоне других, потому что всегда имеют формат ‘ withXXX ‘.
  5. Пакет java.time.zone — классы для поддержки различных часовых поясов и правила их изменения.

Примеры использования Java Date Time API

Мы уже рассмотрели наиболее важные части Java Date Time API. Пришло время разобраться с классами и и посмотреть их в работе на небольших примерах.

Класс java.time.LocalDate

java.time.LocalDate — неизменяемый класс, который представляет объекты Date в формате по умолчанию yyyy-MM-dd . Мы можем использовать метод now() , чтобы получить текущую дату. Мы также можем предоставить в качестве аргументов год, месяц и день, чтобы создать экземпляр LocalDate . Этот класс предоставляет перегруженный метод now() , которому мы можем предоставить ZoneId для получения даты в конкретном часовом поясе. Этот класс предоставляет такую ​​же функциональность как java.sql.Date . Давайте посмотрим на простой пример для его использования:

Читайте также:  Api teams microsoft python

Источник

How to create LocalDateTime in Java 8 — Example Tutorial

The LocalDateTime is a new class introduced in Java 8 new Date and Time API. This class is in java.time package and it represents both date and time information without timezone. In this example, you will learn different ways to create an instance of LocalDateTime class in Java 8 like by using the static factory method, or by combining LocalDate and LocalTime instances together, which are subsequently used to denote date without time and time without the date in Java 8. As their name suggests they are local, so they don’t contain timezone information.

They are always bound to a local timezone i.e. the timezone of the machine on which your Java program is running. The class which contains the date, time and timezone information is known as ZonedDateTime in Java 8.

Many Java programmer thinks that since LocalDateTime contains both date and time information it is equivalent to java.util.Date class which also contains both date and time part, but this is not true. The equivalent class of java.util.Date in the new date and time API is not LocalDateTime but java.time.Instance because the date is nothing a millisecond value from Epoch.

The easiest way to create an instance of the LocalDateTime class is by using the factory method of() , which accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using atDate() and atTime() method of LocalDate and LocalTime class.

Btw, if you are not familiar with the new Date and Time API added on Java 8 then I suggest you first go through a comprehensive and up-to-date Java course like The Complete Java MasterClass on Udemy. It’s also very affordable and you can buy in just $10 on Udemy sales which happen every now and then.


Java 8 LocalDateTime Example

Here is our complete Java program to demonstrate how to use the LocalDateTime class of Java 8. This program first shows the example of creating a LocalDateTime object using the static factory method LocalDateTime.of() which accepts day, month, year, hour, minute, and second and returns the equivalent LocalDateTime instance.

The second example shows how to create the LocalDateTime object by combining LocalDate and LocalTime objects. There is an overloaded factory method that accepts objects of LocalDate and LocalTime for that.

In the last part, I have shown you how to convert a LocalDateTime object to LocalDate and LocalTime in Java 8, which can be very useful if you just need date only or time only information in your project.

import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; /** * Java Program to demonstrate How to use LocalDateTime class in Java 8. * LocalDateTime is LocalDate + LocalTime, i.e. date with time * @author WINDOWS 8 */ public class Java8Demo < public static void main(String args[]) < // LocalDate is date without time in Java 8 // LocalTime is time without date in Java 8 // LocalDateTime is both date and time e.g. LocalDate + LocalTime // but without Timezone information // LocalDateTime.now() creates a LocalDateTieme object with current // date and time LocalDateTime rightNow = LocalDateTime.now(); System.out.println("current datetime : " + rightNow); // LocalDateTime.of() method is a factory method to careate // LocalDateTiem with specific date and time LocalDateTime aDateTime = LocalDateTime.of(2015, Month.JULY, 29, 19, 30, 40); System.out.println("some datetime : " + aDateTime); // You can also create LocalDateTime object by combining LocalDate // and LocalTime LocalDate currentDate = LocalDate.now(); LocalTime currentTime = LocalTime.now(); LocalDateTime fromDateAndTime = LocalDateTime.of(currentDate, currentTime); System.out.println("LocalDateTime created by combining LocalDate" + " and LocalTime" + fromDateAndTime); // You can also retrieve LocalDate and LocalTime from LocalDateTime LocalDate retrievedDate = fromDateAndTime.toLocalDate(); LocalTime retrievedTime = fromDateAndTime.toLocalTime(); System.out.println("retreived LocalDate : " + retrievedDate); System.out.println("retreived LocalTime : " + retrievedTime); > > Output : current datetime : 2015-08-02T00:29:53.949 some datetime : 2015-07-29T19:30:40 LocalDateTime created by combining LocalDate and LocalTime2015-08-02T00:29:53.949 retreived LocalDate : 2015-08-02 retreived LocalTime : 00:29:53.949

How to get LocalDate and LocalTime from LocalDateTime class?

Since LocalDateTime class is nothing but a combination of LocalDate and LocalTime, it’s possible to extract the individual components from this class. You can use the method toLocalDate() to convert a LocalDateTime object to LocalDate in Java 8 and toLocalTime() to get a LocalTime instance from the LocalDateTime object.

LocalDate retrievedDate = fromDateAndTime.toLocalDate(); LocalTime retrievedTime = fromDateAndTime.toLocalTime(); System.out.println("retreived LocalDate : " + retrievedDate); System.out.println("retreived LocalTime : " + retrievedTime);

This is one of the ways you can get LocalDate and LocalTime instances from the LocalDateTime class in Java 8. See Java 8 in Action to learn about more approaches.

Important points:

Here are some of the important points about LocalDateTime class which you should remember to effectively use in Java 8:

1) The LocalDateTime object contains both date and time portions but without timezone. The ZonedDateTime contains the date, time, and timezone information as shown in the following diagram:

How to create LocalDateTime in Java 8 - Example

2) LocalDateTime by default uses the ISO-8601 calendar system, such as 2007-12-03T10:15:30. The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today’s rules for leap years are applied for all time.

3) Like LocalDate and LocalTime, LocalDateTime is also Immutable. Any modification will produce a new object, which means you need to store the result of any date manipulation into another object otherwise modification will be lost.

4) This class has nanosecond precision. For example, the value «2nd October 2007 at 13:45.30.123456789» can be stored in a LocalDateTime.

That’s all about how to use the LocalDateTime class in Java. Just remember that this class represents date and time information without timezone. So it’s very useful to denote certain things which don’t require timezone information.

  • How to parse String to LocalDateTime in Java 8? (tutorial)
  • How to convert java.util.Date to java.time.LocalDateTime in Java 8? (tutorial)
  • How to convert String to LocalDateTime in Java 8? (tutorial)
  • The Best way to convert java.util.Date to java.time.LocalDate in Java 8? (example)
  • How to get a current day, month, and year in Java 8? (tutorial)
  • Java 8 DateTimeFormatter Example (tutorial)
  • 20 Examples of LocalDate, LocalTime, and LocalDateTime in Java 8 (tutorial)

Источник

Оцените статью