SimpleDateFormat in Java is used to format Date in Java. You can format date on any String format based upon various attribute available in SimpleDateFormat class e.g. mm, dd, YY etc. You can also put timezone information in formatted Date using Z attribute of DateFormat class. SimpleDateFormat is sub class of DateFormat and provide format() and parse() method to convert Date to and from String in Java. Worth noting is that SimpleDateFormat is not thread-safe and should not be shared with others. Avoid using static SimpleDateFormat in Java classes. If you want to share SimpleDateFormat or want to make it thread-safe, you can use ThreadLocal variable in Java to avoid sharing SimpleDateFormat among multiple threads. parse() method of SimpleDateFormat throws ParseException if String input is not a valid date or can not be parsed into mentioned format.
How to format Date in Java
In order to format dates using SimpleDateFormat, we first needs to define a String date format e.g. "dd-MM-yyyy" will print dates in that format e.g. 01-11-2012. You can defined format based upon identifiers supported by SimpleDateFormat class. e.g. d means day of month, y means year and M means Month of year. Javadoc of SimpleDateFormat has complete list of supported Date and Time patterns . Once you create a DateFormat, you can just call format() method which accept java.util.Date and returns String, which is formatted Date. In this way you can also convert Date to String in Java. SimpleDateFormat formats date in same pattern which is provided to it while creating instance of SimpleDateFormat. You can also include time information e.g. hour, minutes and seconds while formatting dates by using HH, mm and SS time pattern. DateFormat class also supports inclusion of timezone in formatted date String by z and Z. If you use z you can show timezone information as abbreviation e.g. PST, IST etc. If you use Z you provide timezone, relative to GMT e.g. +0530. In next section we will see couple of SimpleDateFormat example in Java to get hands on on date formatting.
SimpleDateFormat Example in Java
Here is complete code example of How to format Date in Java using SimpleDateFormat. In this example we will see simple date formatting without time information e.g. dd-MM-yyyy, Date formatting with time information with patterns like dd-MM-yyyy:HH:mm:SS and Dates with timezone information in it e.g. dd-MM-yyyy:HH:mm:SS z or dd-MM-yyyy:HH:mm:SS Z.
That's all on these SimpleDateFormat Example in Java. We have seen How to format date with time and timezone information in Java. Though using SimpleDateFormat is most easy way to format Date in Java but it also has its own set of problems. It's not thread-safe and should be used carefully. Avoid using DateFormat as static variable, don't share SimpleDateFormat between multiple threads, result is unpredictable if it's shared among multiple threads.
Other Java programming tutorials you may like