- How to convert Java TimeStamp to Date
- Example 1:
- Example 2:
- Example 3:
- DateTime API in JAVA 8 – TimeStamp and Time Operations
- Get Current TimeStamp as Ms or Sec
- Get Local Date by TimeZone
- Get X Days/Months/Year Early or Later
- LocalDateTime to TimeStamp
- DateTime Formatting
- TimeStamp to DateTime
- String to Date
- String to TimeStamp
- Convert String to Timestamp in Java
- Use TimeStamp.valueOf() to Convert a String to Timestamp in Java
- Use Date.getTime() to Convert a String to Timestamp in Java
- Convert String Date to Timestamp With Timestamp Constructor in Java
- Convert Date String to Timestamp With LocalDate in Java
- Convert String Date to Timestamp With the atStartOfDay() Method in Java
- Related Article — Java DateTime
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); >>
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
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
Convert String to Timestamp in Java
- Use TimeStamp.valueOf() to Convert a String to Timestamp in Java
- Use Date.getTime() to Convert a String to Timestamp in Java
- Convert String Date to Timestamp With Timestamp Constructor in Java
- Convert Date String to Timestamp With LocalDate in Java
- Convert String Date to Timestamp With the atStartOfDay() Method in Java
In this article, we will introduce two methods to convert a string to a timestamp in Java. A timestamp is mainly used in databases to represent the exact time of some event. The Timestamp class we will use in this tutorial is a part of the java.sql.Timestamp package.
Use TimeStamp.valueOf() to Convert a String to Timestamp in Java
We will use the TimeStamp class’s own static function — valueOf() . It takes a string as an argument and then converts it to a timestamp. One important thing to note here is to take care of the format in which the date and time are written in the string that we want to be converted into a timestamp. It is restricted to a fixed format, which is yyyy-mm-dd hh:mm:ss .
We cannot change the format and then expect the right result, but instead, if we use an incorrect format, we will get an IllegalArgumentException in the output. In the below example, we have used 2020-12-12 01:24:23 as the date and time in the string, which follows the correct format of yyyy-mm-dd hh:mm:ss .
We can now pass dateTime as the only argument of the valueOf(string) method, and it will convert a string to a timestamp.
import java.sql.Timestamp; public class StringToTimeStamp public static void main(String[] args) String dateTime = "2020-12-12 01:24:23"; Timestamp timestamp = Timestamp.valueOf(dateTime); System.out.println(timestamp); > >
We can get rid of the date and time formatting restrictions by using the same valueOf() method, but instead of directly passing a string to the method, we will use the LocalDateTime class. Because valueOf() accepts a LocalDateTime as an argument.
In the following code, dateTime has a date and time which is then formatted using the DateTimeFormatter class’s ofPatter() method. We can use this formatter to parse and get a LocalDateTime object using the LocalDateTime.from() function.
Once we get a LocalDateTime object, we can pass it to Timestamp.valueOf(localDateTime) to convert the string to a timestamp.
import java.sql.Timestamp; import java.text.ParseException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class StringToTimeStamp public static void main(String[] args) throws ParseException String dateTime = "01/10/2020 06:43:21"; DateTimeFormatter formatDateTime = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.from(formatDateTime.parse(dateTime)); Timestamp ts = Timestamp.valueOf(localDateTime); System.out.println(ts); > >
Use Date.getTime() to Convert a String to Timestamp in Java
The second method to convert a string to a timestamp uses multiple classes and methods. Just like LocalDateTime , we can use our date and time format in the string. We used the SimpleDateFormate() class to format the string and then parse it to a Date object.
We need the Date object because it has the getTime() object, which returns the date and time as long . We can pass this long value to the constructor of Timestamp as we have done below.
import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToTimeStamp public static void main(String[] args) throws ParseException String inDate = "01/10/2020 06:43:21"; DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date date = df.parse(inDate); long time = date.getTime(); Timestamp ts = new Timestamp(time); System.out.println(ts); > >
Convert String Date to Timestamp With Timestamp Constructor in Java
Here, we use the Timestamp constructor to get a Timestamp object. First, we use the SimpleDateFormat class to set the format of date and then get the date object using the parser() method, then we use the geteTime() method to add time with the date and get a timestamp as a result. See the example below.
import java.util.Date; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class SimpleTesting public static void main(String[] args) try DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = dateFormat.parse("12/10/1990"); Timestamp timeStampDate = new Timestamp(date.getTime()); System.out.println(timeStampDate); > catch (ParseException e) System.out.println(e); > > >
Convert Date String to Timestamp With LocalDate in Java
In Java 8, it adds a new java.time package that contains several classes to deal with date and time. Here, we use the LocalDate class of that package. We use parse() method of LocalDate class to to get LocalDate object from the date string and then use atTime() method to get LocalDateTime object which returns a date with time. The now() is used to get the current time of the system.
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class SimpleTesting public static void main(String[] args) LocalDate date = LocalDate.parse("2025-11-25"); System.out.println(date); LocalDateTime dateTime = date.atTime(LocalTime.now()); System.out.println(dateTime); > >
2025-11-25 2025-11-25T09:44:56.814795
Convert String Date to Timestamp With the atStartOfDay() Method in Java
The atStartOfDay() method in LocalDate class is also use to get LocalDateTime object. This method adds the time to the date at the start of the day and returns a date-time rather than a simple date. See the example below.
import java.time.LocalDate; import java.time.LocalDateTime; public class SimpleTesting public static void main(String[] args) String strDate = "2019-10-20"; LocalDate date = LocalDate.parse(strDate); LocalDateTime dateTime = date.atStartOfDay(); System.out.println(dateTime); > >
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java DateTime
Copyright © 2023. All right reserved