Current date to timestamp java

How to Convert java.util.Date to java.sql.Timestamp

The java.sql.Timestamp extends java.util.Date class, is a thin wrapper to represent SQL TIMESTAMP, which able to keep both date and time. java.sql.Timestamp 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.

Convert java.util.Date to java.sql.Timestamp

java.util.Date to java.sql.Timestamp conversion is necessary when a java.util.Date object needs to be written in a database which the column is used to store TIMESTAMP. Example of this data are last login datetime, transaction creation datetime, etc. java.sql.Timestamp used by JDBC to identify an TIMESTAMP type.

import java.text.DateFormat; import java.text.SimpleDateFormat; public class UtilDateToSqlTimestampExample < public static void main(String[] args) < java.util.Date utilDate = new java.util.Date(); System.out.println("java.util.Date time : " + utilDate); java.sql.Timestamp sqlTS = new java.sql.Timestamp(utilDate.getTime()); System.out.println("java.sql.Timestamp time: " + sqlTS); DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss:SSS"); System.out.println("Date formatted : " + df.format(utilDate)); >> 
java.util.Date time : Fri Aug 02 01:44:51 SGT 2019 java.sql.Timestamp time: 2019-08-02 01:44:51.596 Date formatted : 02/08/2019 01:44:51:596

Per above example, we can convert java.util.Date to java.sql.Timestamp by using the getTime() method of Date class and then pass that value to the constructor of Timestamp object. Date’s getTime() method will return the long millisecond value of that object.

Читайте также:  Align items bottom css

Convert java.util.Timestamp to java.sql.Date

And vice versa, java.sql.Date to java.util.Date conversion is necessary when we need to read TIMESTAMP value from database, and pass it to a java.util.Date variable.

import java.text.DateFormat; import java.text.SimpleDateFormat; public class SqlTimestampToUtilDateExample < public static void main(String[] args) < java.sql.Timestamp sqlTS = java.sql.Timestamp.valueOf("1997-05-07 21:30:55.888"); System.out.println("java.sql.Timestamp time: " + sqlTS); java.util.Date utilDate = new java.util.Date(sqlTS.getTime()); System.out.println("java.util.Date time : " + utilDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss:SSS"); System.out.println("Date formatted : " + df.format(utilDate)); >> 
java.sql.Timestamp time: 1997-05-07 21:30:55.888 java.util.Date time : Wed May 07 21:30:55 SGT 1997 Date formatted : 07/05/1997 09:30:55:888

Putting it All Together

In following example, we will implement the conversion in a simple SQL INSERT and QUERY example. First, we create a test table in our database. As in previous example, this example also using PostgreSQL database. For the sake of showing the difference between DATE datatype and TIMESTAMP datatype, we’ll create a table with both types:

create table test_date ( curr_date DATE, curr_timestamp TIMESTAMP );

The next program demonstrates every step you need to convert current date into a date and a timestamp field, and insert it to database table.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class SqlTimestampInsertExample < public static void main(String[] args) throws Exception < // (1) connect to postgresql database String url = "jdbc:postgresql://localhost/coffeeshop"; Class.forName("org.postgresql.Driver"); try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) < // (2) set java.sql.Date and Timestamp with current Date (and time) java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); java.sql.Timestamp sqlTS = new java.sql.Timestamp(utilDate.getTime()); // (3) insert java.sql.Date and Timestamp to DB String sql = "INSERT INTO test_date(curr_date, curr_timestamp) VALUES (. )"; try (PreparedStatement pst = conn.prepareStatement(sql)) < pst.setDate(1, sqlDate); pst.setTimestamp(2, sqlTS); // (4) execute update pst.executeUpdate(); >> > > 

And now, check the result using psql (result may very):

$ psql coffeeshop barista Password for user barista: psql (9.2.1) Type "help" for help. coffeeshop=> select * from test_date; curr_date | curr_timestamp ------------+------------------------- 2019-08-02 | 2019-08-02 02:17:35.803 (1 row)

From psql console we can see, that DATE is «2019-08-02» and TIMESTAMP is «2019-08-02 02:17:35.803». Now, we create another program to read from database:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class SqlTimestampQueryExample < public static void main(String[] args) throws Exception < // (1) connect to postgresql database String url = "jdbc:postgresql://localhost/coffeeshop"; Class.forName("org.postgresql.Driver"); try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) < // (2) create statement and query Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM test_date"); while ( rs.next() ) < java.sql.Date currSqlDate = rs.getDate("curr_date"); java.sql.Timestamp currSqlTS = rs.getTimestamp("curr_timestamp"); java.util.Date currDate = new java.util.Date(currSqlTS.getTime()); // (3) print results System.out.println("java.sql.Date : " + currSqlDate); System.out.println("java.sql.Timestamp: " + currSqlTS); System.out.println("java.util.Date : " + currDate); >> > > 
java.sql.Date : 2019-08-02 java.sql.Timestamp: 2019-08-02 02:17:35.803 java.util.Date : Fri Aug 02 02:17:35 SGT 2019

And if you curious, what happen is the developer make mistakes, and the datatypes switched?

java.sql.Timestamp currSqlTS = rs.getTimestamp("curr_date"); java.sql.Date currSqlDate = rs.getDate("curr_timestamp"); java.util.Date currDate = new java.util.Date(currSqlTS.getTime()); System.out.println("java.sql.Date : " + currSqlDate); System.out.println("java.sql.Timestamp: " + currSqlTS); System.out.println("java.util.Date : " + currDate); 

Here the result (date/time may vary):

java.sql.Date : 2019-08-02 java.sql.Timestamp: 2019-08-02 00:00:00.0 java.util.Date : Fri Aug 02 00:00:00 SGT 2019

Although not end of the world, the time component is gone for Timestamp.

Conclusion

java.sql.Timestamp used in JDBC to store (and use to retrieve) a TIMESTAMP value. If you need to convert from java.util.Date to java.sql.Timestamp or vice versa, you can use the method getTime() of the source object to get the millisecond value and pass it to target constructor. And again, if you are using Java 8, then better to use new Date/Time API in java.time.* package.

Liked this Tutorial? Share it on Social media!

Источник

How to get current timestamps in Java

This article shows few Java examples to get the current date time or timestamp in Java. (Updated with Java 8).

 // 2021-03-24 16:48:05.591 Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // 2021-03-24 16:48:05.591 Date date = new Date(); Timestamp timestamp2 = new Timestamp(date.getTime()); // convert Instant to Timestamp Timestamp ts = Timestamp.from(Instant.now()) // convert ZonedDateTime to Instant to Timestamp Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant())); // convert Timestamp to Instant Instant instant = ts.toInstant(); 

1. Java Timestamp examples

The below program uses java.sql.Timestamp to get the current timestamp and format the display with SimpleDateFormat .

 package com.mkyong.app; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; public class TimeStampExample < // 2021.03.24.16.34.26 private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss"); // 2021-03-24T16:44:39.083+08:00 private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // 2021-03-24 16:48:05 private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) < // method 1 Timestamp timestamp = new Timestamp(System.currentTimeMillis()); System.out.println(timestamp); // 2021-03-24 16:34:26.666 // method 2 - via Date Date date = new Date(); System.out.println(new Timestamp(date.getTime())); // 2021-03-24 16:34:26.666 // number of milliseconds since January 1, 1970, 00:00:00 GMT System.out.println(timestamp.getTime()); // 1616574866666 System.out.println(sdf1.format(timestamp)); // 2021.03.24.16.34.26 System.out.println(sdf2.format(timestamp)); // 2021-03-24T16:48:05.591+08:00 System.out.println(sdf3.format(timestamp)); // 2021-03-24 16:48:05 >> 
 2021-03-24 16:48:05.591 2021-03-24 16:48:05.591 1616575685591 2021.03.24.16.48.05 2021-03-24T16:48:05.591+08:00 2021-03-24 16:48:05 

2. Convert Instant to/from Timestamp

This example shows how to convert the new Java 8 java.time.Instant to and from the legacy java.sql.Timestamp .

 // convert Instant to Timestamp Timestamp ts = Timestamp.from(Instant.now()) // convert Timestamp to Instant Instant instant = ts.toInstant(); 
 package com.mkyong.app; import java.sql.Timestamp; import java.time.Instant; public class InstantExample < public static void main(String[] args) < Timestamp timestamp = new Timestamp(System.currentTimeMillis()); System.out.println(timestamp); // 2021-03-24 17:12:03.311 System.out.println(timestamp.getTime()); // 1616577123311 // Convert Timestamp to Instant Instant instant = timestamp.toInstant(); System.out.println(instant); // 2021-03-24T09:12:03.311Z System.out.println(instant.toEpochMilli()); // 1616577123311 // Convert Instant to Timestamp Timestamp tsFromInstant = Timestamp.from(instant); System.out.println(tsFromInstant.getTime()); // 1616577123311 >> 
 2021-03-24 17:12:03.311 1616577123311 2021-03-24T09:12:03.311Z 1616577123311 1616577123311 

3. Insert Timestamp into a table

The java.sql.Timestamp is still widely used in JDBC programming. See the below conversions:

 // Java 8, java.time.* // convert LocalDateTime to Timestamp preparedStatement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now())); // convert Instant to Timestamp preparedStatement.setTimestamp(1, Timestamp.from(Instant.now())); // Convert ZonedDateTime to Instant to Timestamp preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant())); 

The below example is a JDBC example of inserting a Timestamp into the table.

 package com.mkyong.app; import java.math.BigDecimal; import java.sql.*; import java.time.LocalDateTime; public class JdbcExample < private static final String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (. )"; public static void main(String[] args) < try (Connection conn = DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password"); PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) < preparedStatement.setString(1, "mkyong"); preparedStatement.setBigDecimal(2, new BigDecimal("799.88")); preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now())); // preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant())); // preparedStatement.setTimestamp(3, Timestamp.from(Instant.now())); int row = preparedStatement.executeUpdate(); // rows affected System.out.println(row); //1 >catch (SQLException e) < System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage()); >catch (Exception e) < e.printStackTrace(); >> > 

4. References

  • Java Date Time Tutorials
  • JDBC PreparedStatement – Insert a row
  • How to get current date time in Java
  • Wikipedia – Epoch time
  • Wikipedia – Timestamp
  • Timestamp
  • LocalDateTime
  • ZonedDateTime
  • Instant
  • Date
  • DateTimeFormatter
  • SimpleDateFormat

Источник

How to Convert Date to Timestamp in Java?

In Java, Date can be converted Timestamp by using Timestamp class. Timestamp class is present in sql package. Date only store date value whereas timestamp stores both date and time value. The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.

Let’s deep dive into this article, to know how it can be done by using Java programming language.

To show you some instances

Instance-1

  • Suppose the input date is written on 05/01/2023.
  • Then corresponding Timestamp is “2023-01-05 20:37:54.832”.

Instance-2

Algorithm:

  • Step-1 − Declare the Date or take a default date from the system.
  • Step-2 − Convert it to timestamp using timestamp class.
  • Step-3 − Print the result.

Syntax

getTime() Method − It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.

Multiple Approaches

We have provided the solution in different approaches.

Let’s see the program along with its output one by one.

Approach-1: By Using Input Date from System

In this approach, we take input date from system. Also, the constructor of Timestamp class receives long value as an argument. So we need to convert date into long value using getTime() method of java.util.Date class.

Example

import java.sql.Timestamp; import java.util.Date; public class Main < //main method public static void main(String args[])< //getting the system date Date date = new Date(); //getting the object of the Timestamp class Timestamp tms = new Timestamp(date.getTime()); // printing the result System.out.println(tms); >>

Output

Approach-2: By Using Input Date as a String

In this approach, we take date input as a String. Also constructor of Timestamp class receives long value as an argument. So we need to convert date into long value using getTime() method of java.util.Date class.

Example

import java.sql.Timestamp; import java.util.Date; public class Main < // Main method public static void main(String[] args)< //taking a string date String date="2022/04/04 04:12:35"; //declaring timestamp Timestamp ts=null; //Intialize date with the string date Date d=new Date(date); // simple null check if(d!=null)< // convert gettime from date and assign it to the timestamp ts=new java.sql.Timestamp(d.getTime()); //printing the timestamp System.out.println(ts); >> >

Output

In this article, we explored different approaches to convert Date to Timestamp by using Java programming language.

Источник

Current date to 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 Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can pass to java.sql.Timestamp. It creates a new instance of the Timestamp object in JDBC. The only way to create a Timestamp instance is to create the constructor of Timestamp class. It accepts a long value as an argument. So you need to convert date into long value using getTime() method of Date class. You can also format the output by using java.text.SimpleDateFormat class. Remember: Timestamp class is a wrapper around Date class to allow JDBC to view it as SQL Timestamp value. The signature of getTime() method of date class is: public long getTime() Example In the following example, we have import two packages namely java.sql.Timestamp and java.util.Date. We have created an object of Date class. Timestamp is a subclass of Date class. We have created a constructor of Timestamp class and passes time as an argument. It returns the current date and time. The println statement prints the data and time.

import java.sql.Timestamp; import java.util.Date; public class DateToTimestampExample < public static void main(String args[]) < Date date = new Date(); Timestamp tstamp=new Timestamp(date.getTime()); System.out.println(tstamp); >>
B.tech
Trending
MCQ
Popular Course

© Copyright 2022 Tutorials & Examples All Rights Reserved.

Источник

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