Sample code to parse date and time with Java SimpleDateFormat

Overview

--Parsing date and time strings with Java's SimpleDateFormat class to stringify Date objects

Sample code

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *Sample to parse format with SimpleDateFormat.
 */
public class Sample {

  public static void main(String[] args) {

    String[] sourceList = {
      "1-2-3 4:5:6",
      "99-2-3 4:5:6",
      "999-2-3 4:5:6",
      "2000-12-31 12:34:56",
      "9999-12-31 12:34:56.0001",
      "9999-12-31 12:34:56.000001",
      "10000-12-31 12:34:56",
      "XXXX-YY-ZZ AA:BB:CC",
      "9999X-12X-31X 12X:34X:56X",
      "X9999-X12-X31 X12:X34:X56",
    };

    parseAndFormat(sourceList, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss");
    parseAndFormat(sourceList, "y-M-d H:m:s", "yyyy-MM-dd HH:mm:ss");
    parseAndFormat(sourceList, "yyyy-MM-dd HH:mm:ss", "y-M-d H:m:s");
  }

  /**
   *Parse and format.
   * @param sourceList Array of strings to parse
   * @param parsePattern Pattern string that parses the datetime string
   * @param formatPattern Date A pattern string that formats an object
   */
  private static void parseAndFormat(String[] sourceList, String parsePattern, String formatPattern) {

    //Prepare the parser
    SimpleDateFormat parser = new SimpleDateFormat(parsePattern);

    //Prepare the formatter
    SimpleDateFormat formatter = new SimpleDateFormat(formatPattern);

    System.out.println("****************************************");
    System.out.println("Parse:  " + parsePattern);
    System.out.println("Format: " + formatPattern);

    for (String source : sourceList) {
      try {
        //Convert date and time string to Date object
        Date date = parser.parse(source);
        //Convert Date object to date and time string
        String text = formatter.format(date);
        System.out.println(source + " -> " + text);
      } catch (ParseException e) {
        System.out.println(source + " -> " + e.toString());
      }
    }

    System.out.println();
  }
}

Execution result

Example executed on Java 8 (AdoptOpenJDK 1.8.0_272-b10) + macOS Catalina.

****************************************
Parse:  yyyy-MM-dd HH:mm:ss
Format: yyyy-MM-dd HH:mm:ss
1-2-3 4:5:6 -> 0001-02-03 04:05:06
99-2-3 4:5:6 -> 0099-02-03 04:05:06
999-2-3 4:5:6 -> 0999-02-03 04:05:06
2000-12-31 12:34:56 -> 2000-12-31 12:34:56
9999-12-31 12:34:56.0001 -> 9999-12-31 12:34:56
9999-12-31 12:34:56.000001 -> 9999-12-31 12:34:56
10000-12-31 12:34:56 -> 10000-12-31 12:34:56
XXXX-YY-ZZ AA:BB:CC -> java.text.ParseException: Unparseable date: "XXXX-YY-ZZ AA:BB:CC"
9999X-12X-31X 12X:34X:56X -> java.text.ParseException: Unparseable date: "9999X-12X-31X 12X:34X:56X"
X9999-X12-X31 X12:X34:X56 -> java.text.ParseException: Unparseable date: "X9999-X12-X31 X12:X34:X56"

****************************************
Parse:  y-M-d H:m:s
Format: yyyy-MM-dd HH:mm:ss
1-2-3 4:5:6 -> 0001-02-03 04:05:06
99-2-3 4:5:6 -> 1999-02-03 04:05:06
999-2-3 4:5:6 -> 0999-02-03 04:05:06
2000-12-31 12:34:56 -> 2000-12-31 12:34:56
9999-12-31 12:34:56.0001 -> 9999-12-31 12:34:56
9999-12-31 12:34:56.000001 -> 9999-12-31 12:34:56
10000-12-31 12:34:56 -> 10000-12-31 12:34:56
XXXX-YY-ZZ AA:BB:CC -> java.text.ParseException: Unparseable date: "XXXX-YY-ZZ AA:BB:CC"
9999X-12X-31X 12X:34X:56X -> java.text.ParseException: Unparseable date: "9999X-12X-31X 12X:34X:56X"
X9999-X12-X31 X12:X34:X56 -> java.text.ParseException: Unparseable date: "X9999-X12-X31 X12:X34:X56"

****************************************
Parse:  yyyy-MM-dd HH:mm:ss
Format: y-M-d H:m:s
1-2-3 4:5:6 -> 1-2-3 4:5:6
99-2-3 4:5:6 -> 99-2-3 4:5:6
999-2-3 4:5:6 -> 999-2-3 4:5:6
2000-12-31 12:34:56 -> 2000-12-31 12:34:56
9999-12-31 12:34:56.0001 -> 9999-12-31 12:34:56
9999-12-31 12:34:56.000001 -> 9999-12-31 12:34:56
10000-12-31 12:34:56 -> 10000-12-31 12:34:56
XXXX-YY-ZZ AA:BB:CC -> java.text.ParseException: Unparseable date: "XXXX-YY-ZZ AA:BB:CC"
9999X-12X-31X 12X:34X:56X -> java.text.ParseException: Unparseable date: "9999X-12X-31X 12X:34X:56X"
X9999-X12-X31 X12:X34:X56 -> java.text.ParseException: Unparseable date: "X9999-X12-X31 X12:X34:X56"

Reference material

Recommended Posts

Sample code to parse date and time with Java SimpleDateFormat
Check the actual date and time at parse with Java's SimpleDateFormat
Handle Java 8 date and time API with Thymeleaf with Spring Boot
[MySQL] [java] Receive date and time
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
Link Java and C ++ code with SWIG
[Java] How to set the Date time to 00:00:00
Java 8 to start now ~ Date time API ~
Java sample code 02
Java sample code 03
Java sample code 04
Java sample code 01
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
[Java] How to get the current date and time and specify the display format
Minimum configuration sample to automatically release Lambda by Java with Code pipeline
Code that is difficult to debug and parse
Try to link Ruby and Java with Dapr
[Java] Explanation of Strategy pattern (with sample code)
[Java] How to use Calendar class and Date class
Parse the date and time string formatted by the C asctime function in Java
[Java] Date / time operations
Sample code to convert List to List <String> in Java Stream
Change date and time to Japanese notation in Rails
[Rails] Precautions when comparing date and time with DateTime
I want to transition screens with kotlin and java!
How to build Java development environment with VS Code
Link Docker log to AWS CloudWatch and monitor in real time with VS Code
JavaFX application development with IntelliJ IDEA and Gradle ~ From environment construction to sample code ~
How to decompile apk file to java source code with MAC
Digital signature sample code (JAVA)
Java to play with Function
What is the LocalDateTime class? [Java beginner] -Date and time class-
Java source sample (Oracle Database + java) to SELECT and display CLOBs
Java code sample to acquire and display DBLINK source and destination data in Oracle Database using DBLINK
I want to make a list with kotlin and java!
Set the date and time from the character string with POI
I want to make a function with kotlin and java!
Connect to DB with Java
Connect to MySQL 8 with Java
Difficult to handle minimum values for Java8 LocalDateTime and Java6 Date
I want to implement various functions with kotlin and java!
A memo to start Java programming with VS Code (2020-04 version)
Sample code for basic mocking and testing with Mockito 3 + JUnit 5
I want to return to the previous screen with kotlin and java!
Convert line feed code to html line feed tag with Thymeleaf and output
Settings to delete unused Java imports when saving with VS Code
The relationship between strict Java date checking and daylight savings time
How to manage Java code automatically generated by jOOQ & Flyway sample
Sample code to unit test a Spring Boot controller with MockMvc
[With sample code] Basics of Spring JDBC to learn with Blog app
Sample code to call the Yahoo! Local Search API in Java
Sample to read and write LibreOffice Calc fods file in Java 2021
How to encrypt and decrypt with RSA public key in Java
Java to learn with ramen [Part 1]
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Code Java from Emacs with Eclim
[Java] Points to note with Arrays.asList ()
Java 15 implementation and VS Code preferences
Dare to challenge Kaggle with Java (1)
Use JDBC with Java and Scala.