- Преобразование даты java.util в дату, отметку времени и время java.sql в Java
- 1. Конвертировать java.util.Date к java.sql.Date
- How to convert Timestamp to Date in Java?JDBC Example Tutorial
- Java Program to convert Timestamp to Date with example
- Important points
- How to convert Java TimeStamp to Date
- Example 1:
- Example 2:
- Example 3:
Преобразование даты 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 объект.
How to convert Timestamp to Date in Java?JDBC Example Tutorial
In the last article, I have shown you how to convert Date to Timestamp in Java and today we’ll learn about converting timestamp value from database to Date in Java. As you remember, the JDBC API uses separate Date , Time, and Timestamp classes to confirm DATE, TIME, and DATETIME data type from the database, but most of the Java object-oriented code is written in java.util.Date . This means you need to know how to convert the timestamp to date and vice-versa. You can do by using the getTime() method, which returns the number of millisecond from Epoch value.
This can be used to create both Timestamp and java.util.Date , hence it acts as a bridge between Date class from java.util package and Date, Time and Timestamp class from the java.sql package. Like Date, Timestamp also contains both date and time value, so you won’t see empty or zero time we saw previously while converting SQL Date to java.util.Date.
As I have said before, even though classes from java.sql package extends java.util.Date, including Timestamp they cannot be used in place of java.util.Date . Some of you may ask why? Since Timestamp has both date and time value, it should be able to acts as Date, we understand about java.sql.Date not having a time component but with Timestamp, we have both.
Well, that’s again very good reasoning and directs your mind to find the missing part of why you cannot use Timestamp in place of date even if it has both date and time part. The answer lies in the Java documentation itself.
The Timestamp class is a composite of java.util.Date and additional nanoseconds values, required to hold the SQL TIMESTAMP fractional seconds value. If you look at the implementation of the Timestamp class, you will find that 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 e.g. Timestamp.equals(date) will return false even if they contain the same value 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, hence it also violates the contract of equals method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include Nanos in its computation.
Btw, If you want to refresh your concepts of equals and hashcode, I suggest you reading Effective Java, where Joshua Bloch has discussed it in great detail.
So even though, methods like getHours() , getMinutes() , getSeconds() don’t throw IllegalArgumentException , because of these differences, you still should not use a Timestamp value in place of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
Java Program to convert Timestamp to Date with example
Now, let’s see our sample Java program to convert a Timestamp value to Date in Java. In this example, our Java program connects to the Microsoft SQL server and calls the CURRENT_TIMESTAMP method using the PreparedStatment object. This method returns the current database system timestamp as a DATETIME value without the database time zone offset.
This value is derived from the operating system of the computer on which the instance of SQL Server is running (see SQL fundamentals).
When we read this value in Java using ResultSet, we use the getTimestamp() method and pass it to the column index. If you remember, columns in JDBC API start with 1 instead of zero, we pass 1. We also need to call the next() method of ResultSet to move the cursor to the first element, otherwise, you won’t the correct value.
Once you got the java.sql.Timestamp value, just call the getTime() and create a java.util.Date instance using that. Now, you have successfully converted a java.sql.Timestamp value to java.util.Date value. You can further check these free JDBC courses to learn more bout it.
Program to convert Timestamp to Date in Java
import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Date; /* * Java Program to convert Timestamp to Date in JDBC. */ public class Pattern < public static void main(String[] args) < Timestamp timestamp = timeStampFromDatabase(); Date date = new java.util.Date(timestamp.getTime()); System.out.println("current timestamp from database: " + timestamp); System.out.println("converted date in Java: " + date); > public static Timestamp timeStampFromDatabase() < Connection con = null; Timestamp currentTimeStamp = null; try < Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://localhost:42588;"; DriverManager.setLogWriter(new PrintWriter(System.out, true)); con = DriverManager.getConnection(url, "sa", "root"); PreparedStatement ps = con.prepareStatement("select CURRENT_TIMESTAMP"); ResultSet rs = ps.executeQuery(); rs.next(); // move the cursor to first column currentTimeStamp = rs.getTimestamp(1); > catch (Exception e) < e.printStackTrace(); >return currentTimeStamp; > > Output DriverManager.getConnection("jdbc:sqlserver://localhost:42588;") trying sun.jdbc.odbc.JdbcOdbcDriver *Driver.connect (jdbc:sqlserver://localhost:42588;) trying com.microsoft.sqlserver.jdbc.SQLServerDriver getConnection returning com.microsoft.sqlserver.jdbc.SQLServerDriver current timestamp from database: 2016-06-17 13:13:56.61 converted date in Java: Fri Jun 17 13:13:56 PST 2016
A couple of important things to learn in this program, first, I have not called the Class.forName() method to explicitly load the JDBC driver because from Java 1.6 onward, it can be automatically loaded by JVM. The second important thing is the use of setting the logger for DriverManager , which will print important details e.g. which JDBC driver it is loading and which host and port it is connecting to the database.
The code to convert Timestamp into a java.util.Date is inside main() method, you can see it’s quite simple, just take the long millisecond value by calling getTime() on Timestamp and pass it to Date constructor, that’s it, you are done.
You can further read Core Java, Volume II—Advanced Features by Cay S. Horstmann to learn more about JDBC driver and other JDBC concepts, one of the most useful books to learn Java concepts.
Important points
1.Timestamp class has both date and time value as Date but cannot be used in place of java.util.Date because of additional nanosecond value it supports.
2. The Timestamp.equals(Object) method will return false if you compare Timestamp with Date, this is one of the reasons you cannot use Timestamp in place of Date in Java.
3. The Timestamp class has «s» instead of «S» which you might expect given most of the Java classes are written using the Camel case. Another one is Hashtable with «t» instead of «T»
4. Columns are started with index 1 instead of zero hence getTimestamp(1) is used. This is not just related to Timestamp but related to ResultSet in JDBC and you must remember this to avoid java.sql.SQLException: Invalid column index, which often comes when a programmer tries to access the first column with index zero, which is invalid.
5. Don’t forget to call ResultSet.next() method before calling get() even if it contains just one row. It is required to move the cursor to the first element. It’s a tricky concept to master but if you don’t know the right way to check if ResultSet is empty or not, you will struggle to write robust JDBC code in the future.
That’s all about how to convert a Timestamp to Date in Java. As a programmer working with Java, JDBC, and database you must know these details about Timestamp and Date class, it’s imperative to write correct JDBC code. Unfortunately, Java could have done a better job by standardizing things, as it’s a drawback of an API if the programmer needs to remember so many exceptional cases.
How to convert Java TimeStamp to Date
In Java, TimeStamp can be converted into Date using the constructor of the Date class of the java.util package.
It must be noted that Date class takes an argument as a long value hence the TimeStamp object needs to be converted into long. This is done using the getTime() method of Timestamp class of the java.sql package.
Example 1:
Here, the TimeStamp is converted into Date by using the Date constructor. See the example below.
import java.sql.Timestamp; import java.util.Date; public class StudyTonight < public static void main(String args[]) < Timestamp t = new Timestamp(System.currentTimeMillis()); //for current time in milliseconds Date d = new Date(t.getTime()); System.out.println(d); >>
Thu Sep 24 05:28:11 UTC 2020
Example 2:
Also, the Timestamp class extends the Date class. Hence, the instance of the Timestamp class can directly be assigned into Date and the output like Timestamp can be obtained. But, it is undesirable because the milliseconds and nanoseconds can be lost in this case.
import java.sql.Timestamp; import java.util.Date; public class StudyTonight < public static void main(String args[]) < Timestamp t = new Timestamp(System.currentTimeMillis()); Date d = t; System.out.println(d); >>
Example 3:
Here, the TimeStamp is converted into Date with formatting into various formats.
import java.sql.Timestamp; import java.text.DateFormat; import java.util.Date; import java.text.SimpleDateFormat; public class StudyTonight < public static void main(String args[]) < Timestamp stamp = new Timestamp(System.currentTimeMillis()); Date date = new Date(stamp.getTime()); DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); DateFormat f1 = new SimpleDateFormat("yyyy/MM/dd"); String d = f.format(date); String d1 = f1.format(date); System.out.println(d); System.out.println(d1); >>