import java.text.ParseException;
public class Hello {
public static void main(String[] args) throws ParseException {
System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd").parse("23-06-2015"));
}
}
why this returns Sun Dec 05 00:00:00 GMT 28
I am expecting an exception.
Create Simple Date Format // Date Format In Java String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); According to the example above, the String pattern will be used to format dates, and the output will be shown as "yyyy-MM-dd".
2.2.Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. So SimpleDateFormat instances are not thread-safe, and we should use them carefully in concurrent environments.
What can I use instead of SimpleDateFormat? You can use the DateTimeFormatter class in JDK 8 to change the date format of String in Java 8. The steps are exactly the same but instead of using SimpleDateFormat and Date class, we'll use the DateTimeFormatter and LocalDateTime class.
The java SimpleDateFormat allows construction of arbitrary non-localized formats. The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.
The Javadoc for SimpleDateFormat
has this to say about repeated pattern letters:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields
(Emphasis mine)
So for parsing, "yyyy-MM-dd"
is equivalent to "y-M-d"
.
With this pattern, "23-06-2015"
is parsed as year = 23, month = 6, dayOfMonth = 2015
.
By default, this gets resolved by starting at 1st June 0023, and counting 2015 days forward, taking you to 5th December 0028.
You can change this behaviour with SimpleDateFormat.setLenient(false)
-- with leniency disabled, it will throw an exception for out-of-range numbers. This is properly documented in Calendar.setLenient()
Note, for new code in Java 8, it's a good idea to avoid the old Date
and Calendar
classes. Use LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter)
if you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With