Phoenix Phoenix - 10 months ago 36
Java Question

How do I convert the date from one format to another date object in another format without using any deprecated classes?

I'd like to convert a date in date1 format to a date object in date2 format.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 21);
Date date = cal.getTime();
Date date1 = simpleDateFormat.parse(date);
Date date2 = simpleDateFormat.parse(date1);
println date1
println date2


Use SimpleDateFormat#format:

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date);  // 20120821

Also note that parse takes a String, not a Date object, which is already parsed.