Today I want to show you some examples of how you can use SimpleDateFormat class in your code. I hope some of them will be new and surprising!
The basic example
First the most basic usage of the class. Lets use it to format Date object into a simple string showing day, month and a year:
1: | SimpleDateFormat simpleDateFormat = |
Slightly more advanced
Obviously we can use more complicated patterns than that (see SimpleDateFormat JavaDoc for the full list). Besides adding more data to be shown we can also add some regular text – to do that in a pattern you need to escape the text with an apostrophe. So here is a fancy way of printing the time and date:
1: | SimpleDateFormat simpleDateFormat = |
Now with Locale
SimpleDateFormat is Locale dependent, so by providing one you can get the Date string localized for specific language or country. This is a date in French:
1: | SimpleDateFormat simpleDateFormat = |
Parse String to Date
Good thing about the SimpleDateFormat class is that it can be used not only for formatting, but also for parsing string into a Date object. In this example the used pattern is exactly the same as used by Date.toString() method. With it we can parse the strings created by Data.toString() back into dates:
1: | // SimpleDateFormat that works exactly like Date.toString() |
Setting the default time zone
Notice that when you parse a string into a Date the result may be ambiguous. For example the string “11:23 1 Jan 2001″ is a different moment in time depending whether you live in Japan or Canada. By default Java resolves this by using your local time zone obtained from the default Locale.
Since the time zone may not be a part of the parsed string you may want to set it manually instead using the default one. You can do this with setTimeZone() method:
1: | SimpleDateFormat simpleDateFormat = |
Setting the century
Similar ambiguity occurs when parsing two-digit year dates. Whether “01/01/59″ is the new year’s day of 1959 or 2059 can be set by specifying the century to the SimpleDateFormat object. To be specific with set2DigitYearStart() method you can specify the 100 year period in which the parsed date will be placed. By default the 100 year period is [today - 80 years, today + 20 years]. See the example:
1: | SimpleDateFormat simpleDateFormat = |
Make the parsing more strict
By default the parse method of SimpleDateFormat is very forgiving. If the provided string is not entirely compatible with the pattern, SimpleDateFormat instead of giving up tries with many tricky heuristics to guess what would be the correct answer. In many situations this behavior is more than welcome, but if you do not like this you can disable it. With setLenient() method you can make the parsing obey exactly the pattern and throw an exception if string is invalid.
1: | SimpleDateFormat simpleDateFormat = |