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.
A date can be in various formats. Here are few

Let’s 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 the timezone parameter and formatter will do the rest for you.
0 Comments