Sunday 22 July 2012

How to convert String to Date in java?

The SimpleDateFormat class offers a method called parse( ), which can be used to parse a string into java.util.Date object according to the format stored in the given SimpleDateFormat object.


A pattern of special characters is used to specify the format of the date.For example, dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on.For a complete listing, see the table given below.



Date and Time Patterns


Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation.All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):



Symbol Meaning Type Example
G Era Text “GG” -> “AD”
y Year Number “yy” -> “03″
“yyyy” -> “2003″
M Month Text or Number “M” -> “7″
“M” -> “12″
“MM” -> “07″
“MMM” -> “Jul”
“MMMM” -> “December”
d Day in month Number “d” -> “3″
“dd” -> “03″
h Hour (1-12, AM/PM) Number “h” -> “3″
“hh” -> “03″
H Hour (0-23) Number “H” -> “15″
“HH” -> “15″
k Hour (1-24) Number “k” -> “3″
“kk” -> “03″
K Hour (0-11 AM/PM) Number “K” -> “15″
“KK” -> “15″
m Minute Number “m” -> “7″
“m” -> “15″
“mm” -> “15″
s Second Number “s” -> “15″
“ss” -> “15″
S Millisecond (0-999) Number “SSS” -> “007″
E Day in week Text “EEE” -> “Tue”
“EEEE” -> “Tuesday”
D Day in year (1-365 or 1-364) Number “D” -> “65″
“DDD” -> “065″
F Day of week in month (1-5) Number “F” -> “1″
w Week in year (1-53) Number “w” -> “7″
W Week in month (1-5) Number “W” -> “3″
a AM/PM Text “a” -> “AM”
“aa” -> “AM”
z Time zone Text “z” -> “EST”
“zzz” -> “EST”
“zzzz” -> “Eastern Standard Time”
Excape for text Delimiter “‘hour’ h” -> “hour 9″
Single quote Literal “ss”SSS” -> “45’876″



parse(String text):


This method is used to parse date/time string into date. The return type of this method is Date. This method throws ParseExceptionParse Exception if the given string cannot be parsed as a date.



For example:



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

public class StringToDate {

 public static void main(String[] args) {
  try {

   String str_date = "12-12-1987:10:20:56";
   SimpleDateFormat formatter;
   Date date;

   formatter = new SimpleDateFormat("dd-MM-yyyy:hh:mm:ss");
   date = (Date) formatter.parse(str_date);

   System.out.println("Created Date object is:" + date);

  } catch (ParseException e) {
   System.out.println("Exception :" + e);
  }

 }

}


The output is

No comments:

Post a Comment