Wednesday, July 9, 2014

Java util date string to date conversion(new java.util.Date().tostring() to Date object)

Converting java.util.Date string value in Date object

 DateHandler.java

    public static Date convertDate(String date, String pattern)
            throws Exception {
        logger.info("Entering into the class DateHandler: convertDate()...");
        Date dt = null;
        try {
            if (pattern == null || pattern.trim().length() == 0) {
                pattern = ""; // you can set your default pattern like "ddd MMM dd HH:mm:ss GMT yyyy"
            }
            DateFormat sf = new SimpleDateFormat(pattern);
            dt = sf.parse(date);
        } catch (Throwable e) {
        //    logger.error(" error on date format.." + e);          
        }
        logger.info("Exit from the class DateHandler: convertDate()...");
        return dt;
    }



Testing the conversion:


    public static void main(String[] args) {
        try {
            // String pattern ="ddd MMM dd HH:mm:ss GMT yyyy";
  
               String UTIL_DATE_FORMAT = "EEE MMM dd HH:mm:ss zzz yyyy";

                String inputDtString = new Date().toString(); //sample value would be "Tue Jul 08 14:23:25 EDT 2014"

                  System.out.println(" Date after conversion--->"
                                                     + convertDate(inputDtString, UTIL_DATE_FORMAT);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 






output :

Date after conversion ---->  Tue Jul 08 14:23:25 EDT 2014

No comments:

Post a Comment