Let’s start with 2 basic rules to follow

  • Convert Date (java.util.Date) into String => format
  • Convert String into Date => parse

I have used SimpleDateFormat which extends DateFormat of java.text package.

Date can be in various format. Here are few

Screen Shot 2015-09-26 at 11.14.15

Lets see an Example

public class DateConverter {

    private static final String DATE_TIME_FORMAT = "dd-MMM-yyyy HH:mm";

    public static Date convertStringToDate(String srcDate)
    throws ParseException {
        DateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT);
        return formatter.parse(srcDate);
    }

    public static String convertDateToString(Date srcDate) {
        DateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT);
        return formatter.format(srcDate);
    }

    public static void main(String[] args) throws ParseException {
        try {
            System.out.println(convertStringToDate("12-May-2014 12:30"));
            System.out.println(convertDateToString(new Date()));
        } catch (ParseException pe) {
            throw pe;
        }
    }

    // Output:
    // Mon May 12 12:30:00 IST 2014
    // 26-Sep-2015 11:42

}

Note: Suppose we need to convert String Date format to another String Date format. Implementing above rules, Convert String => Date => String

Handling Timezone

public class TimezoneConversion {

    private static final String DATE_TIME_FORMAT = "dd-MMM-yyyy HH:mm";

    public static void convertDateTime(Date srcDate, String timezone) {
        DateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone(timezone));
        String date = formatter.format(srcDate);
        System.out.println(new Date());
    	System.out.println(date);
	}

	public static void main(String[] args) {
		convertDateTime(new Date(), "US/Pacific");
	}
    //Output :
    //Sat Sep 26 12:25:21 IST 2015
    //25-Sep-2015 23:55
}

To get Date time for a particular timezone just pass timezone parameter and formatter will do the rest for you.

Categories: JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

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