How to Convert String Date to Timestamp

JavaJavaBeginner
Practice Now

Introduction

String date can be converted to a timestamp using the SimpleDateFormat, Timestamp and Date class of Java. This lab will cover two ways to convert date string to timestamp.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/date("`Date`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/classes_objects -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/date -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/exceptions -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/modifiers -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/oop -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/packages_api -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/identifier -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/arrays -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/comments -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/data_types -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/operators -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/output -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/strings -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/variables -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/string_methods -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} java/system_methods -.-> lab-117426{{"`How to Convert String Date to Timestamp`"}} end

Convert String to Date using the parse() method

import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;

public class StringToTimestamp {
    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);
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

To run this program, open the terminal and navigate to the ~/project/ directory.

Convert String date to Timestamp using the 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 there is no need to do overhead coding.

import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;

public class StringToTimestamp {
    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);
        }
    }
}

Compile and run the program

Open the terminal and navigate to the ~/project/ directory. Use the following command to compile and then run the code:

javac StringToTimestamp.java && java StringToTimestamp

Handle Incorrect Date Format

If the string is in the incorrect format you will get an exception error: java.text.ParseException: Unparseable date:. To handle this error, we can add a catch block to display an error message.

import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;

public class StringToTimestamp {
    public static void main(String[] args) throws Exception {
        // date in string format
        String stringDate = "2021-01-07 02:02:16";
        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);
        } catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Convert Epoch Time to Timestamp

Convert epoch time to timestamps using the following code:

import java.sql.Timestamp;

public class StringToTimestamp {
    public static void main(String[] args) throws Exception {
        // epoch time
        long epochTime = 1609934536172L;
        try {
            // create Timestamp object
            Timestamp timestamp = new Timestamp(epochTime);
            System.out.println(timestamp);
        } catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Convert Timestamp to String

Convert Timestamp to string format using SimpleDateFormat.

import java.text.SimpleDateFormat;
import java.sql.Timestamp;

public class StringToTimestamp {
    public static void main(String[] args) throws Exception {
        // timestamp
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        try {
            // create SimpleDateFormat object
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
            // format Timestamp object
            String formattedDate = dateFormat.format(timestamp);
            // print formatted date
            System.out.println(formattedDate);
        } catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Using Calendar Class

Instead of SimpleDateFormat, we can also use the Calendar class to convert string date to timestamp.

import java.util.Calendar;
import java.sql.Timestamp;

public class StringToTimestamp {
    public static void main(String[] args) throws Exception {
        // string date
        String stringDate = "2021-01-07 02:02:16.172";
        try {
            // create Calendar object
            Calendar calendar = Calendar.getInstance();
            // set calendar date with string date
            calendar.setTime(new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(stringDate));
            // convert calendar to timestamp
            java.sql.Timestamp timestamp = new java.sql.Timestamp(calendar.getTimeInMillis());
            System.out.println(timestamp);
        } catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Using ZonedDateTime Class

We can also convert string date to timestamp using the ZonedDateTime class.

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.sql.Timestamp;

public class StringToTimestamp {
    public static void main(String[] args) throws Exception {
        // string date
        String stringDate = "2021-01-07 02:02:16.172";
        try {
            // create DateTimeFormatter object and specify the format of the string date
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            // create ZonedDateTime object and parse the string date
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(stringDate, formatter.withZone(ZoneId.systemDefault()));
            // convert ZonedDateTime to timestamp
            Timestamp timestamp = Timestamp.valueOf(zonedDateTime.toLocalDateTime());
            System.out.println(timestamp);
        } catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Run the Program

Open the terminal and navigate to the ~/project/ directory. Use the following command to compile and then run the code:

javac StringToTimestamp.java && java StringToTimestamp

Summary

In this lab, we have learned how to convert a String date to a Timestamp in Java using different ways including SimpleDateFormat, Timestamp, Date, Calendar, and ZonedDateTime class. The SimpleDateFormat and Timestamp methods are the easiest to implement while the ZonedDateTime method is the most complicated but offers the most flexibility.

Other Java Tutorials you may like