Convert string to date format in android
try {
String strDate = "Jan 17, 2012";
//current date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date objDate = dateFormat.parse(strDate);
//Expected date format
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
I suggest using Joda Time, it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).
You use it this way:
// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");
// Result: 2012-01-17
It also provides plenty of useful methods for operations on dates (add day, time difference, etc.). And it provides interfaces to most of the classes for easy testability and dependency injection.
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
Which produces this output when run in the PDT time zone:
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
For more info look at here