Перевести дату в timestamp java

How to Convert String Date to Timestamp in Java

In this tutorial, we will learn how to convert String Date to Timestamp in Java. This conversion is very important when we want to deal with timestamps. For example, one may be interested to know which date is smaller than the other, or we may want to count the number of days since a particular date and it is not possible with the string date. In this tutorial, we will use SimpleDateFormat , Timestamp , and Date class of Java.

Example for converting String a Date to Timestamp

The code is given below works perfectly for converting String Date to Timestamp. Firstly we will convert a simple string to Date using SimpleDateFormat.parse() method before that makes sure that timestamp is given in the correct format.

import java.text.SimpleDateFormat; import java.sql.Timestamp; import java.util.Date; public class StudyTonight < public static void main(String[] args) throws Exception < //date in string format String stringDate = "2021-01-07 02:02:16.172"; try < //creating date format SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); //parsing string to date using parse() method Date parsedDate = dateFormat.parse(stringDate); //finally creating a timestamp Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime()); System.out.println(timestamp.getClass()); >catch(Exception e) < System.out.println(e); >> > 

If the string is in the incorrect format you will get an exception error: java.text.ParseException: Unparseable date:

Читайте также:  Set background opacity css

Converting String date to Timestamp using valueOf() Method

This is another way of converting date string to timestamp using valueOf() method of java.sql.Timestamp class. This is a simple method and no need to do overhead coding.

Example 2

In this program, we do not need to think about a format for a date because valueOf() method will directly convert the string to the timestamp itself. Unlike the last code if the string is not in the correct format it will throw an exception java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff].

import java.text.SimpleDateFormat; import java.sql.Timestamp; import java.util.Date; public class StudyTonight < public static void main(String[] args) throws Exception < //date in string format String stringDate = "2021-01-07 02:02:16.172"; try < //converting string date to timestamp using valueOf() method java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf( stringDate ); System.out.println(timestamp); >catch(Exception e) < System.out.println(e); >> >

Conclusion:

To convert the string date to timestamp we have two ways i.e. using TimeStamp as a constructor and another is using a valueOf() method of TimeStamp class. This is very useful when it comes to performing operations on actual timestamps rather than different formats of date.

Источник

Перевести дату в timestamp java

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

How to convert java.util.Date to java.sql.Timestamp? Example Tutorial

You can convert a java.util.Date to java.sql.Timestamp value by using the getTime() method of Date class. This method returns the long millisecond value from Epoch (1st January 1970 midnight) which you can pass to java.sql.Timestamp to create a new instance of Timestamp object in JDBC. Remember, java.sql.TimeStamp class is a wrapper around java.util.Date to allow JDBC to view it as SQL TIMESTAMP value. The only way to create a Timestamp instance is by passing the long time value because the second constructor of the Timestamp class, which accepts individual fields like a year, month, date, hour, minute, second, and nano is deprecated. Timestamp class can also hold up to nanosecond value.

Even though it’s a wrapper around Date class and contains both date and time fields it cannot be used in place of Date because it doesn’t honor equals() contract i.e. when you compare Date with Timestamp it returns true but it returns false for the same object if you compare Timestamp to Date.

In other words, two instances of Date and Timestamp with the same millisecond value will return true if you compare them using the equals() method of Date class i.e. date.equals(timestamp) will return true.

But, when you change the order i.e. compare them using Timestamp’s equals() method like timestamp.equals(date) the result will be false. This is against the symmetry property of equals contract which says if x.equals(y) is true then y.equals(x) should also be true.

This difference comes due to many factors and one of them is additional nanosecond precision which Timestamp needs to support. You can see my earlier article about why you cannot use Timestamp in place of Date in Java to learn more about this interesting topic.

In this tutorial, you will learn how to convert a java.util.Date to java.sql.TimeStamp and vice-versa. Btw, if you are new to JDBC and looking for a comprehensive online course to learn JDBC in-depth then I also suggest you check out the Complete JDBC Programming course on Udemy. It’s a great course of direct classroom lectures and covers JDBC in depth

java.util.Date to java.sql.Timestamp and vice-versa

Here is the code to convert a java.util.Date instance to java.sql.TimeStamp object in JDBC. The code is using the same technique which we have used in the past to convert java.util.Date to java.sql.Date i.e. extracting the long millisecond value from Date and using it to create an instance of Timestamp class

Date now = new Date(); Timestamp ts = new Timestamp(now.getTime());

And here is code for the opposite side i.e. converting a java.sql.Timestamp value to java.util.Date in Java:

Timestamp now = new Timestamp(); Date date = new Date(now.getTime());

You can see it’s quite simple, nothing complicated, just a couple of lines of code, and you are done. Though, if you want to learn more about data and time classes in JDBC, I suggest you join these online advanced core Java courses to learn about advanced concepts. This also contains JDBC courses to explains all important JDBC concepts in simple language.

Difference between java.util.Date and java.sql.TimeStamp

As I told you before, the java.sql.Timestamp is not exactly same as java.util.Date object, because its a composite of java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component, fractional seconds i.e. Nanos are separate.

This means Timestamp.equals(date) may return false if you pass a Date that is equal in value. This is the sole reason why Timestamp cannot be used in place of Date in JDBC.

This class should only be used while reading DATETIME values from databases e.g. SQL Server. You can then convert that column into a Timestamp object in the DAO layer and finally into a java.util.Object in your application layer.

If you want to learn more about the Timestamp class in java.sql package and how to use it while interacting with databases from Java applications, please see the Java: How to Program by Deitel and Deitel, one of the rare complete books for Java programmers.

How to convert java.util.Date to java.sql.Timestamp?

Important points

1) The java.sql.Timestamp is equivalent to SQL TIMESTAMP type in Java. It also maps to Types.TIMESTAMP

2) The setTimestamp() method is used to store Timestamp value from Java to Database.

3) The java.sql.TimeStamp method extends java.util.Date , but its composite of Date + nano second value

4) It’s possible that date.equals(timestamp) == true but timestamp.equals(date) == false because equals() method of Timestamp class is not symmetric, hence violates equals contract.

5) The hashCode() method of java.sql.Timestamp class uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.

6) Similar to Hashtable which doesn’t follow the camel case, Timestamp also has small ‘s’ i.e. doesn’t follow the camel case so, don’t write TimeStamp .

That’s all about how to convert a java.util.Date to java.sql.TimeStamp value in JDBC. Remember, even though java.sql.Timestamp extends java.util.Date , its not a type inheritance, in-fact it’s just an implementation inheritance. Timestamp class also violates the Liskov Substitution principle hence you cannot use Timestamp in place of Date in Java.

  • Difference between java.util.Date and java.sql.Date in JDBC? (answer)
  • Difference between java.sql.Time, java.sql.Timestamp, and java.sql.Date in JDBC? (answer)
  • How to convert java.util.Date to java.sql.Date in JDBC? (example)
  • How to convert java.sql.Date to java.util.Date in JDBC? (example)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (example)
  • Why is String class made final in Java? (answer)
  • Why Hibernate Entity class should not be final in Java? (answer)
  • Why Timestamp cannot be used in place of Date in Java? (answer)

Thanks for reading this article so far. If you find this article and example useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

Источник

Преобразование даты java.util в дату, отметку времени и время java.sql в Java

В этом посте мы обсудим, как конвертировать java.util Дата до java.sql Дата, временная метка и время в Java.

Мы знаем, что реляционные базы данных, такие как Oracle, MySQL, поддерживают типы данных DATE, TIME и TIMESTAMP. Все эти типы данных имеют соответствующий класс в JDBC, и каждый из них расширяет java.util.Date . В этом посте мы обсудим, как конвертировать java.util Date к этим классам:

1. Конвертировать java.util.Date к java.sql.Date

Java имеет два Date классов, один из присутствующих в java.util пакет и другие присутствующие в java.sql упаковка. java.sql.Date соответствует SQL DATE содержит информацию о годе, месяце и дне, в то время как информация о часах, минутах, секундах и миллисекундах отсутствует.

Преобразование из java.util.Date к java.sql.Date на самом деле очень просто в Java. Конструктор java.sql.Date ожидает миллисекунды, прошедшие с начала эпохи (1 января 1970 г., 00:00:00 по Гринвичу), которые можно получить с помощью getTime() метод java.util.Date объект.

результат:

java.util.Date : Thu Jan 24 21:53:32 GMT 2015
java.sql.Date : 2015-01-24

Начиная с Java 8, мы должны предпочесть использовать Instant класс из java.time пакет, похожий на java.util Date класса, но дает наносекундную точность. java.time.LocalDateTime (дата-время без часового пояса), java.time.ZonedDateTime (дата-время с часовым поясом), LocalDate (дата без часового пояса) и LocalTime (время без часового пояса) также были введены в Java 8 и выше.

Поскольку тип данных SQL DATE только для даты, без информации о времени и часовом поясе, лучше использовать java.time.LocalDate класс, а не java.util.Date в Java 8 и выше. Мы можем создать LocalDate например, получая сегодняшнюю дату в соответствии с конкретным часовым поясом.

Теперь, чтобы преобразовать java.time.LocalDate к java.sql.Date , мы можем использовать valueOf() метод, недавнее добавление в Java 8 и выше, который может получить экземпляр java.sql.Date из java.time.LocalDate объект.

Источник

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