Progress28.ru

IT Новости


09ae9cb0
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java sql time

16. Java — Дата и время

Java предоставляет класс Date, который доступен в пакете java.util, этот класс заключает в себе текущую дату и время.

Содержание

Конструкторы

Класс Date поддерживает два конструктора, которые показаны ниже.

Конструктор и описание
1Date()
Этот конструктор инициализирует объект с текущей датой и временем.
2Date(long millisec)
Этот конструктор принимает аргумент равный числу миллисекунд, истекших с полуночи 1 января 1970 г.

Методы класса Date

Ниже представлены методы класса Date.

Методы с описанием
1boolean after(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, которая раньше заданной даты, в противном случае он возвращает значение false.
2boolean before(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, более раннюю, чем заданная дата, в противном случае он возвращает значение false.
3Object clone()
Дублирование вызывающего объекта date.
4int compareTo(Date date)
Сравнивает значение вызывающего объекта с этой датой. Возвращает 0, если значения равны. Возвращает отрицательное значение, если объект вызова является более ранним, чем дата. Возвращает положительное значение, если объект вызова позже даты.
5int compareTo(Object obj)
Работает точно так же compareTo(Date), если объект вызова имеет класс Date. В противном случае вызывает ClassCastException.
6boolean equals(Object date)
Возвращает значение true, если вызывающий объект date содержит то же время и дату, которая указана в date, в противном случае он возвращает значение false.
7long getTime()
Возвращает количество миллисекунд, истекших с 1 января 1970 года.
8int hashCode()
Возвращает хэш-код для вызывающего объекта.
9void setTime(long time)
Задает дату и время, соответствующие моменту времени, что представляет собой общее затраченное время в миллисекундах от полуночи 1 января 1970 года.
10String toString()
Преобразует вызывающий объект date в строку и возвращает результат.

Текущая дата и время в Java

Получить текущую дату и время в Java достаточно не трудно. Вы можете использовать простой объект date вместе с методом toString(), чтобы вывести текущую дату и время следующим образом:

Получим следующий результат:

Сравнение дат

Существуют три способа в Java сравнить даты:

  • Можно использовать функцию getTime(), чтобы получить количество миллисекунд, прошедших с момента полуночи 1 января 1970, для обоих объектов, а затем сравнить эти два значения.
  • Вы можете использовать методы before(), after() и equals(). Поскольку 12 число месяца раньше 18 числа, например, new Date(99, 2, 12).before(new Date (99, 2, 18)) возвращает значение true.
  • Можно использовать метод compareTo(), который определяется сопоставимым интерфейсом и реализуется по дате.

Форматирование даты с помощью SimpleDateFormat

SimpleDateFormat — это конкретный класс для парсинга и форматирования даты в Java. SimpleDateFormat позволяет начать с выбора любых пользовательских шаблонов для форматирования даты и времени. Например:

Получим следующий результат:

Формат-коды SimpleDateFormat

Для того, чтобы задать в Java формат даты и времени, используйте строковый шаблон (регулярные выражения) с датой и временем. В этой модели все буквы ASCII зарезервированы как шаблон письма, которые определяются следующим образом:

СимволОписаниеПример
GОбозначение эрын.э.
yГод из четырех цифр2016
MНомер месяца года11
dЧисло месяца13
hФормат часа в A.M./P.M.(1

12)

7
HФормат часа(0

23)

19
mМинуты30
sСекунды45
SМиллисекунды511
EДень неделиВс
DНомер дня в году318
FНомер дня недели в месяце2 (второе воскресение в этом месяце)
wНомер неделя в году46
WНомер недели в месяце2
aМаркер A.M./P.M.AM
kФормат часа(1

24)

24
KФормат часа в A.M./P.M.(0

11)

zЧасовой поясFET (Дальневосточноевропейское время)
Выделение для текстаТекст
»Одинарная кавычка

Форматирование даты с помощью printf

Формат даты и времени можно сделать без труда с помощью метода printf. Вы используете формат двух букв, начиная с t и заканчивая одним из символов в таблице, приведенных ниже. Например:

Получим следующий результат:

Было бы немного глупо, если Вы должны были бы поставить дату несколько раз для форматирования каждой части. По этой причине формат строки может указывать индекс аргумента для форматирования.

Индекс должен непосредственно следовать за % и завершаться $. Например:

java sql date time

When I insert a SQL DateTime to the database I get 2007-02-07 12:00:00.00

But I made the Date object like this : 2007-02-07 17:29:46.00

How to get the value of the seconds in the database. It always changes it back to 12:00:00.00

Should I use any formatters?

2 Answers 2

java.sql.Date represents a date, not a date and time. From the docs:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

If you want to store a date and time, you should look for another type — e.g. java.sql.Timestamp . EDIT: That’s not suggesting you use a TIMESTAMP column type — as paulsm4 says in the comments, that’s a different thing. However, as far as I can see, JDBC only supports:

  • Date (no, you want a time too)
  • Time (no, you want a date too)
  • Timestamp (includes a date and time, but you don’t want TIMESTAMP SQL semantics)

I would expect using the Java Timestamp type with a DATETIME column to work, although without the level of precision that Timestamp provides.

EDIT: After a bit more research, it looks like you may want to use the java.sql.Time type, but with special driver parameters — at least if you’re using the Microsoft driver. See these docs on configuring JDBC for more information.

You are likely confused by not understanding that java.util.Date is a date-with-time type while its subclass java.sql.Date pretends to be a date-only class but actually has its time-of-day set to zero. Bloody awful design. Avoid both these classes entirely. Use java.time classes only.

For a date-only column in your database, define the column as the SQL-standard DATE type.

java.time

The modern approach uses the java.time classes added to Java 8 and later.

When I insert a SQL DateTime to the database I get 2007-02-07 12:00:00.00

There is no such thing as a SQL-standard type as DateTime , nor any such class in Java. So I do not know your intention there.

As for the input string, 2007-02-07 17:29:46.00 , parse that as a LocalDateTime because it lacks any indicator of time zone or offset-from-UTC.

That SQL-style format almost complies with the ISO 8601 standard. To fully comply, replace the SPACE in the middle with a T . The java.time classes use the ISO 8601 formats by default when parsing/generating strings.

A LocalDateTime does not represent a moment, is not a point on the timeline. It represents potential moments along a range of about 26-27 hours.

Standard SQL does offer a data type for such a value, TIMESTAMP WITHOUT TIME ZONE .

Smart objects, not dumb strings

Your entire approach is misguided, wrangling text and using the legacy date-time classes. Instead, exchange java.time objects.

As of JDBC 4.2, you need not ever use the troublesome old java.sql types such as java.sql.Date or java.sql.Timestamp . You can directly exchange java.time objects with your database via setObject / getObject methods.

If you are trying to work with date-only values, use the SQL-standard type DATE and the Java class LocalDate .

How to get the value of the seconds in the database

Not sure what you mean by «value of the seconds».

Perhaps you want a count of seconds from the epoch reference of first moment of 1970 in UTC.

If your goal was merely to instantiate a java.sql.Date , don’t bother. Never use that class again. But, FYI, your specific issue is likely a side-effect of the awful design used for that class. The java.sql.Date class inherits from java.util.Date which is a date-with-time type. The java.sql.Date class pretends to be a date-only value, but actually has its time-of-day set to 00:00:00. Even worse, the documentation tells us to ignore the fact of its being a subclass. Don’t bother trying to understand it; just use java.time instead.

If you are trying to work with the time-of-day alone, extract a LocalTime object.

If you want to set the time-of-day to zeros, then you likely want a date-only value. If so, use the LocalDate class for a date value without a time-of-day and without a time zone.

If you do want the first moment of the day on that date, call LocalDate::atStartOfDay .

BEWARE: If you are trying to track actual moments, specific points on the timeline, then all this code above is wrong. Search Stack Overflow to learn about Instant , ZoneId , and ZonedDateTime classes. Search both Stack Overflow and dba.StackExchange.com to learn about the SQL-standard type TIMESTAMP WITH TIME ZONE .

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

JPA 2.2 Support for Java 8 Date/Time Types

Last modified: January 24, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

The JPA 2.2 version has officially introduced the support for Java 8 Date and Time API. Before that, either we had to rely on a proprietary solution, or we had to use the JPA Converter API.

In this tutorial, we’ll show how to map the various Java 8 Date and Time types. We’ll especially focus on the ones that take into account the offset information.

2. Maven Dependencies

Before we start, we need to include the JPA 2.2 API to the project classpath. In a Maven based project, we can simply add its dependency to our pom.xml file:

Additionally, to run the project, we need a JPA implementation and the JDBC driver of the database that we’ll be working with. In this tutorial, we’ll use EclipseLink and the PostgreSQL database:

Feel free to check the latest versions of JPA API, EclipseLink, and PostgreSQL JDBC driver on Maven Central.

Of course, we can use other databases or JPA implementations like Hibernate.

3. TimeZone Support

We can work with any database, but first, we should check the support for these Standard SQL Types, as the JDBC 4.2 is based on:

  • TIMESTAMP(n) WITH TIME ZONE
  • TIMESTAMP(n) WITHOUT TIME ZONE
  • TIME(n) WITH TIME ZONE
  • TIME(n) WITHOUT TIME ZONE

Here, n is the fractional seconds precision and is between 0 and 9 digits. WITHOUT TIME ZONE is optional and can be omitted. If WITH TIME ZONE is specified, the timezone name or the offset to UTC is required.

We can represent the timezone in one of these two formats:

  • Timezone name
  • Offset from UTC or the letter Z for UTC

For our example, we’ve chosen the PostgreSQL database thanks to its full support for the SQL Type TIME WITH TIME ZONE.

Note that other databases may not support these types.

4. Mapping Date Types Before Java 8

Before Java 8, we usually had to map the generic SQL types TIME, DATE, and TIMESTAMP, to either the java.sql.* classes java.sql.Time, java.sql.Date, and java.sql.Timestamp, respectively, or to java.util types java.util.Date and java.util.Calendar.

First, let’s see how to use the java.sql types. Here, we’re simply defining the attributes with java.sql types as part of an @Entity class:

While the java.sql types work like any other types without any additional mapping, the java.util types need to specify the corresponding temporal types.

This is done through the @Temporal annotation whose value attribute allows us to specify the corresponding JDBC type, using the TemporalType enumeration:

Note that if we’re using Hibernate as an implementation, this doesn’t support mapping Calendar to TIME.

Similarly, we can use the Calendar class:

None of these types have support for the timezone or the offset. To deal with those pieces of information, we traditionally had to store the UTC time.

5. Mapping Java 8 Date Types

Java 8 has introduced the java.time packages, and the JDBC 4.2 API added support for the additional SQL types TIMESTAMP WITH TIME ZONE and TIME WITH TIME ZONE.

We can now map the JDBC Types TIME, DATE, and TIMESTAMP to the java.time typesLocalTime, LocalDate, and LocalDateTime:

Additionally, we have support for the offset local timezone to UTC through the OffsetTime and OffsetDateTime classes:

The corresponding mapped column types should be TIME WITH TIME ZONE and TIMESTAMP WITH TIME ZONE. Unfortunately, not all databases support these two types.

As we can see, JPA supports these five classes as basic types, and there’s no additional information needed to distinguish between the date and/or the time information.

After saving a new instance of our entity class, we can check that data has been inserted correctly:

6. Conclusion

Before Java 8 and JPA 2.2, developers usually had to convert date/time types to UTC before persisting them. JPA 2.2 now supports this feature out of the box by supporting the offset to UTC and by leveraging JDBC 4.2 support for the timezone.

The full source code for these samples can be found over on Github.

Читать еще:  Разработка веб приложений javascript
Ссылка на основную публикацию