Get timestamp as string in java

Java sql.Timestamp toString() method with example

The toString() method of the java.sql.Timestamp class returns the JDBC escape format of the time stamp of the current Timestamp object as String variable.

i.e. using this method you can convert a Timestamp object to a String.

//Retrieving the Time object Timestamp timestampObj = rs.getTimestamp("DispatchTimeStamp"); //Converting the Time object to String format String time_stamp = timestampObj.toString();

Example

Let us create a table with the name dispatches_data in MySQL database using CREATE statement as shown below:

CREATE TABLE dispatches_data( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchTimeStamp timestamp, Price INT, Location VARCHAR(255));

Now, we will insert 5 records in dispatches_data table using INSERT statements:

insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad'); insert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam'); insert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada'); insert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai'); insert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');

Following JDBC program establishes a connection with the database and retrieves the contents of the dispatches_data table.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; public class Timestamp_toString < public static void main(String args[]) throws SQLException < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); //Query to retrieve the contents of the dispatches_data table String query = "select * from dispatches_data"; //Executing the query ResultSet rs = stmt.executeQuery(query); while (rs.next()) < System.out.println("Product Name: " + rs.getString("ProductName")); System.out.println("Customer Name: " + rs.getString("CustomerName")); Timestamp timeStampObj = rs.getTimestamp("DispatchTimeStamp"); //Converting the Time object to String format String timeStamp = timeStampObj.toString(); System.out.println("Dispatch time stamp in String format: " + timeStamp); System.out.println("Location: " + rs.getString("Location")); System.out.println(); >> >

Here, in this program while retrieving the column values, we have converted the DeliveryTime value from the Timestamp object to string format using the toString() method of the Timestamp class and trying to display it.

Output

Connection established. Product Name: Key-Board Customer Name: Raja Dispatch time stamp in String format: 2019-05-04 15:02:45.0 Location: Hyderabad Product Name: Earphones Customer Name: Roja Dispatch time stamp in String format: 2019-06-26 14:13:12.0 Location: Vishakhapatnam Product Name: Mouse Customer Name: Puja Dispatch time stamp in String format: 2019-12-07 07:50:37.0 Location: Vijayawada Product Name: Mobile Customer Name: Vanaja Dispatch time stamp in String format: 2018-03-21 16:00:45.0 Location: Chennai Product Name: Headset Customer Name: Jalaja Dispatch time stamp in String format: 2018-12-30 10:49:27.0 Location: Goa

Источник

Читайте также:  Php json encode library

DateTime API in JAVA 8 – TimeStamp and Time Operations

In this article, we’ll share some basic DateTime conversion by using DateTime API of Java 8 that you would need in a project. Working with Dates, trying to convert them into the proper format is always a pain in the ass. After Java 8, a new DateTime API is introduced.

We’ll basically work on examples.

Get Current TimeStamp as Ms or Sec

You need to use Instant object to get the timestamp. You can get the timestamp as milliseconds or second.

Instant instant = Instant.now(); long timeStampMillis = instant.toEpochMilli(); System.out.println(timeStampMillis);

Output: 1549057795923

Instant instant = Instant.now(); long timeStampMillis = instant.getEpochSecond(); System.out.println(timeStampMillis);

Output: 1549057795

Get Local Date by TimeZone

You can use LocalDate object to get the current system date. You are able to pass ZoneId object to change the time zone.

LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:00")); System.out.println("GMT+2 " + localDate.toString()); localDate = LocalDate.now(ZoneId.of("GMT+05:00")); System.out.println("GMT+5 " + localDate.toString());

According to the hour that you run that code, you might have the same result or a different one. As a one-time zone might have started to live the next already 🙂

Get X Days/Months/Year Early or Later

There are very handy methods coming with LocalDate object. You can add, subtract days, months, years or even week to a given date and get the new date object.

LocalDate date = LocalDate.now(ZoneId.of("GMT+02:00")); System.out.println("Today " + date.toString()); LocalDate earlyDay = date.minusDays(3); System.out.println("Past " + earlyDay.toString()); LocalDate futureDay = date.plusDays(3); System.out.println("Future "+futureDay.toString());
LocalDate date = LocalDate.now(ZoneId.of("GMT+02:00")); System.out.println("Today " + date.toString()); LocalDate earlyMonth = date.minusMonths(3); System.out.println("Past " + earlyMonth.toString()); LocalDate futureMonth = date.plusMonths(3); System.out.println("Future "+futureMonth.toString());

You can also add or subtract week or year with other methods.

LocalDateTime to TimeStamp

You might need to convert a date object to timestamp. Here’s how you can achieve this challenge.

LocalDate date = LocalDate.now(ZoneId.of("GMT+02:00")); LocalDate earlyDay = date.minusDays(dayCount); LocalDateTime dateTime = earlyDay.atStartOfDay(); Timestamp t = Timestamp.valueOf(dateTime); System.out.println("TimeStamp is "+t.getTime());

Output: TimeStamp is 1549882173000

DateTime Formatting

String FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; LocalDateTime date = LocalDateTime.now(ZoneId.of("GMT+02:00")); System.out.println("Today " + date.format(DateTimeFormatter.ofPattern(FORMAT)));

Output: Today 2019-02-02 08:55:47.208

Example Formats:

yyyy-MM-dd (2009-11-30) dd-MM-YYYY (31-11-2008) yyyy-MM-dd HH:mm:ss (2009-08-30 22:58:59) HH:mm:ss.SSS (22:58.59.999) yyyy-MM-dd HH:mm:ss.SSS (2009-11-30 22:58:59.999) yyyy-MM-dd HH:mm:ss.SSS Z (2009-11-30 22:58:59.999 +0100)
y = year (yy or yyyy) M = month (MM) d = day in month (dd) h = hour (0-12) (hh) H = hour (0-23) (HH) m = minute in hour (mm) s = seconds (ss) S = milliseconds (SSS) z = time zone text (e.g. Pacific Standard Time. ) Z = time zone, time offset (e.g. -0800)

TimeStamp to DateTime

String FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; Instant instant = Instant.now(); long timeStampMillis = instant.toEpochMilli(); ZoneId zone = ZoneId.systemDefault(); DateTimeFormatter df = DateTimeFormatter.ofPattern(FORMAT).withZone(zone); String time = df.format(Instant.ofEpochMilli(timeStampMillis)); System.out.println("Formatted Date " + time);

Output: Formatted Date 2019-02-02 09:33:33.084

String to Date

String dateInString = "26 Aug 1985"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM yyyy", Locale.ENGLISH); LocalDate dateTime = LocalDate.parse(dateInString, formatter); System.out.println("Parsed Date " +dateTime.toString());

Output: Parsed Date 1985-08-26

String to TimeStamp

String timestampString = "2018-11-27T16:30:00.21234Z"; Instant inst = Instant.parse(timestampString); System.out.println("String to TimeStamp "+inst.toEpochMilli());

Output: String to TimeStamp 1543336200212

Читайте также:  Javascript to escape html tags

Hope those will help when you need to deal with Dates. In case you encounter any problems and questions, just let us know by commenting so we add new examples.

Canberk Akduygu is a Test Lead working in the Netherlands

Источник

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.

Читайте также:  Nginx 404 для php

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.

Источник

Get timestamp as string in java

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)

Источник

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