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.