text

Parse custom formatted date with SimpleDateFormat

With this example we are going to demonstrate how to parse custom formatted date with SimpleDateFormat. SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows formatting (date -> text), parsing (text -> date), and normalization. In short, to parse custom formatted date with SimpleDateFormat you should:

  • Create a new SimpleDateFormat, using a String pattern. The pattern describes the date and time format.
  • Invoke the parse(String source) API method to parse text from the beginning of the given string to produce a date. It will return a Date parsed from the string.

Let’s take a look at the code snippet that follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.javacodegeeks.snippets.core;
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ParseCustomFormattedDateWithSimpleDateFormat {
     
    public static void main(String[] args) {
         
         
        try {
             
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
             
            // parse string in custom format into date object
            Date date = df.parse("10/11/2011 16:24");
            System.out.println(date);
             
        }
        catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe.getMessage());
        }
         
    }
 
}

Output:

Thu Nov 10 16:24:00 EET 2011

 
This was an example of how to parse custom formatted date with SimpleDateFormat in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button