Real'sHowTo AddThis Feed Button
Custom Search

Parse a String to obtain a Date/GregorianCalendar objectTag(s): Date and Time


import java.util.Date;
import java.util.Locale;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class DateUtils {

 public static Calendar parseTimestamp(String timestamp)
    throws Exception {
   /*
   ** we specify Locale.US since months are in english
   */
   SimpleDateFormat sdf = new SimpleDateFormat
     ("dd-MMM-yyyy HH:mm:ss", Locale.US);
   Date d = sdf.parse(timestamp);
   Calendar cal = Calendar.getInstance();
   cal.setTime(d);
   return cal;
 }

 public static void main (String a[]) throws Exception{
   String timestampToParse = "24-Feb-1998 17:39:35";
   System.out.println("Timestamp : " +  timestampToParse);

   SimpleDateFormat sdf =
          new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   System.out.println("Calendar : "
      + sdf.format(parseTimestamp(timestampToParse).getTime()));
   /*
   output :
     Timestamp : 24-Feb-1998 17:39:35
     Calendar : 1998-02-24 17:39:35
   */
 }

}

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]