- Java timestamp текущая дата
- Constructor Summary
- Method Summary
- Methods declared in class java.util.Date
- Methods declared in class java.lang.Object
- Constructor Detail
- Timestamp
- Timestamp
- Method Detail
- setTime
- getTime
- valueOf
- toString
- getNanos
- setNanos
- Class Timestamp
- Class Timestamp
- Java timestamp текущая дата
- Methods inherited from class java.util.Date
- Methods inherited from class java.lang.Object
- Constructor Detail
- Timestamp
- Timestamp
- Method Detail
- setTime
- getTime
- valueOf
- toString
- getNanos
- setNanos
- equals
- equals
- before
- after
- compareTo
- compareTo
- hashCode
- valueOf
- toLocalDateTime
- from
- toInstant
- Java Blog
- 1. java.sql.Timestamp
- 2. java.time.Instant
- Комментарии
- Отправить комментарий
- Популярные сообщения из этого блога
- Методы класса Object в Java
- Spring Boot стартеры
Java timestamp текущая дата
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds — the nanos — are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn’t an instance of java.sql.Timestamp , because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date . The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
Constructor Summary
Method Summary
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .
Methods declared in class java.util.Date
Methods declared in class java.lang.Object
Constructor Detail
Timestamp
@Deprecated(since="1.2") public Timestamp(int year, int month, int date, int hour, int minute, int second, int nano)
Timestamp
public Timestamp(long time)
Constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
Method Detail
setTime
public void setTime(long time)
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
getTime
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
valueOf
toString
Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff , where fffffffff indicates nanoseconds.
getNanos
setNanos
public void setNanos(int n)
Class Timestamp
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.
- 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss
- 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.[fff. ] and s represents the scale of the given Timestamp, its fractional seconds precision.
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds — the nanos — are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn’t an instance of java.sql.Timestamp , because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date . The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
Class Timestamp
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.
- 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss
- 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.[fff. ] and s represents the scale of the given Timestamp, its fractional seconds precision.
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds — the nanos — are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn’t an instance of java.sql.Timestamp , because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date . The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
Java timestamp текущая дата
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .
Methods inherited from class java.util.Date
Methods inherited from class java.lang.Object
Constructor Detail
Timestamp
@Deprecated public Timestamp(int year, int month, int date, int hour, int minute, int second, int nano)
Timestamp
public Timestamp(long time)
Constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
Method Detail
setTime
public void setTime(long time)
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
getTime
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
valueOf
toString
Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff , where ffffffffff indicates nanoseconds.
getNanos
setNanos
public void setNanos(int n)
equals
equals
Tests to see if this Timestamp object is equal to the given object. This version of the method equals has been added to fix the incorrect signature of Timestamp.equals(Timestamp) and to preserve backward compatibility with existing class files. Note: This method is not symmetric with respect to the equals(Object) method in the base class.
before
after
compareTo
compareTo
hashCode
Returns a hash code value for this object. The result is the exclusive OR of the two halves of the primitive long value returned by the Date.getTime() method. That is, the hash code is the value of the expression:
(int)(this.getTime()^(this.getTime() >>> 32))
The hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
valueOf
public static Timestamp valueOf(LocalDateTime dateTime)
Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime . The provided LocalDateTime is interpreted as the local date-time in the local time zone.
toLocalDateTime
Converts this Timestamp object to a LocalDateTime . The conversion creates a LocalDateTime that represents the same year, month, day of month, hours, minutes, seconds and nanos date-time value as this Timestamp in the local time zone.
from
Obtains an instance of Timestamp from an Instant object. Instant can store points on the time-line further in the future and further in the past than Date . In this scenario, this method will throw an exception.
toInstant
Converts this Timestamp object to an Instant . The conversion creates an Instant that represents the same point on the time-line as this Timestamp .
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
Java Blog
Вот еще два более подробных примера как получить текущий timestamp в Java:
1. java.sql.Timestamp
Есть два метода получить текущий java.sql.Timestamp
package main; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; public class Main < private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss"); public static void main(String[] args) < // Метод 1 Timestamp timestamp = new Timestamp(System.currentTimeMillis()); System.out.println(timestamp); // Метод 2 - через Date Date date = new Date(); System.out.println(new Timestamp(date.getTime())); // возвращает количество миллисекунд с 1 января 1970, 00:00:00 GMT System.out.println(timestamp.getTime()); // форматированный timestamp System.out.println(dateFormat.format(timestamp)); > >
2019-10-03 10:20:11.114 2019-10-03 10:20:11.114 1570080011114 2019.10.03.10.20.11
2. java.time.Instant
В Java 8 вы можете преобразовать java.sql.Timestamp в новый java.time.Instant
package main; import java.sql.Timestamp; import java.time.Instant; public class Main < public static void main(String[] args) < Timestamp timestamp = new Timestamp(System.currentTimeMillis()); System.out.println(timestamp); // возвращает количество миллисекунд с 1 января 1970, 00:00:00 GMT System.out.println(timestamp.getTime()); // Преобразуем timestamp в instant Instant instant = timestamp.toInstant(); System.out.println(instant); // возвращает количество миллисекунд с эпохи 1970-01-01T00:00:00Z System.out.println(instant.toEpochMilli()); // Преобразуем instant в timestamp Timestamp tsFromInstant = Timestamp.from(instant); System.out.println(tsFromInstant.getTime()); >>
2019-10-03 10:24:54.255 1570080294255 2019-10-03T05:24:54.255Z 1570080294255 1570080294255
- Получить ссылку
- Электронная почта
- Другие приложения
Комментарии
Отправить комментарий
Популярные сообщения из этого блога
Методы класса Object в Java
Класс Object является корнем иерархии классов. У каждого класса есть Object как суперкласс. Все объекты, включая массивы, реализуют методы этого класса. Методы класса Object Метод getClass() public final Class getClass() Возвращает класс времени исполнения (runtime class) этого Object. Возвращенный объект Class — это объект, который заблокирован статическими синхронизированными методами представленного класса. Фактический тип результата — Class где |X| заменяется статическим типом выражения, для которого вызывается getClass. Например, в этом фрагменте кода не требуется приведение: Number n = 0; Class c = n.getClass(); Метод getClass() возвращает: Объект Class, представляющий класс времени исполнения (runtime class) этого объекта. Метод hashCode public int hashCode() Возвращает значение хэш-кода для объекта. Этот метод поддерживается для использования хэш-таблиц, таких как те, что предоставляются HashMap. Основной контракт метода hashCo?>
Spring Boot стартеры
Стартеры — это набор удобных дескрипторов зависимостей, которые вы можете включить в свое приложение. Вы получаете универсальный набор для всех необходимых вам Spring и связанных с ними технологий без необходимости искать примеры кода и копировать и вставлять множество дескрипторов зависимостей. Например, если вы хотите начать использовать Spring и JPA для доступа к базе данных, включите в ваш проект зависимость spring-boot-starter-data-jpa. Стартеры содержат множество зависимостей, которые необходимы вам для быстрого запуска и запуска проекта с согласованным, поддерживаемым набором управляемых переходных зависимостей. Что указывается в имени стартера Все официальные стартеры следуют аналогичной схеме именования; spring-boot-starter-*, где * это конкретный тип приложения. Эта структура наименования предназначена, чтобы помочь, когда вам нужно найти стартер. Интеграция Maven во многие IDE позволяет вам искать зависимости по имени. Например, если установлен соответствующий плагин Ecl