Converting Date to a certain String format
suggest changeSimpleDateFormat.format converts a Date to a String with the given pattern. SimpleDateFormat is not thread-safe. The comments below match 25 February 2016 at 06:14:33 in Locale.US; MMM and E depend on the formatter's locale.
Calendar calendar = Calendar.getInstance();
calendar.set(2016, Calendar.FEBRUARY, 25, 6, 14, 33);
calendar.set(Calendar.MILLISECOND, 0);
Date today = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy", Locale.US);
System.out.println(dateFormat.format(today)); // 25-Feb-16
Call applyPattern to change the pattern on the same formatter:
dateFormat.applyPattern("dd-MM-yyyy");
System.out.println(dateFormat.format(today)); // 25-02-2016
dateFormat.applyPattern("dd-MM-yyyy HH:mm:ss E");
System.out.println(dateFormat.format(today)); // 25-02-2016 06:14:33 Thu
Note: mm means minutes and MM means the month. Lower-case y is the calendar year. Upper-case Y is the week-year, not the week number. The week of the year is w.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents