Using SimpleDateFormat to convert a date in string into a desired format
SimpleDateFormat sdfYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd"); // The input date string will be in yyyy-MM-dd format
SimpleDateFormat sdfDDMMMYYYY = new SimpleDateFormat("dd-MMM-yyyy"); //The output date string will be in dd-MMM-yyyy format
Date date;
try {
date = sdfYYYYMMDD.parse("2012-12-09"); // Parse the input string into a date object. parse method throws a ParseException
System.out.println(date); // Prints as Sun Dec 09 00:00:00 IST 2012
String formattedDate = sdfDDMMMYYYY.format(date); // Format the date object to a string in the dd-MMM-yyyy (desired format).
System.out.println(formattedDate); // Prints as 09-Dez-2012
} catch (ParseException e) {
e.printStackTrace();
}
If we need to use sorting on dates, say for using Collections.sort(list), we implement Comparable interface and override the compareTo() method.
@Override
public int compareTo(EmpTable o) {
String dateinstr1 = this.getDate();
String dateinstr2 = o.getDate();
try{
SimpleDateFormat sdfyyyymmdd = new SimpleDateFormat("dd-MMM-yyyy");
Date date1 = sdfyyyymmdd.parse(dateinstr1);
Date date2 = sdfyyyymmdd.parse(dateinstr2);
return date1.compareTo(date2);
}catch(ParseException e){
e.printStackTrace();
}
return 0;
}
If dates are as Date objects, the above piece of code can be used for displaying dates in ascending format.
If they need to be in descending format, the highlighted text above needs to be written as
return - date1.compareTo(date2);
i.e., prefix with a minus sign.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment