Home > Java > javaTutorial > Why Does SimpleDateFormat Throw 'Unparseable Date'?

Why Does SimpleDateFormat Throw 'Unparseable Date'?

Susan Sarandon
Release: 2025-01-01 02:22:09
Original
317 people have browsed it

Why Does SimpleDateFormat Throw

Unparseable Dates with SimpleDateFormat: Specify Locale or Use DateTimeFormatter

Problem:
When using SimpleDateFormat to parse dates, you may encounter the error "java.text.ParseException: Unparseable date," especially when the locale is not specified.

Explanation:
SimpleDateFormat requires a locale to parse dates correctly. If none is specified, it uses the system's default locale, which may not match the format being parsed.

Solution:

  1. Always specify the locale: Use SimpleDateFormat's constructor overload that accepts a Locale argument. For example:
SimpleDateFormat dtfmt = new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH);
Copy after login
  1. Use the modern DateTimeFormatter API:
  • DateTimeFormatter is the preferred API for formatting and parsing dates and times.
  • It provides greater flexibility and control over formatting, including the ability to specify a locale.

Demo with DateTimeFormatter:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "24 Oct 2016 7:31 pm";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d MMM uuuu h:m a").withLocale(Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
        System.out.println(ldt); // prints 2016-10-24T19:31
    }
}
Copy after login

Note:

  • The default locale specified by DateTimeFormatter uses the system's current locale.
  • Always explicitly specify the locale to avoid potential parsing issues.

The above is the detailed content of Why Does SimpleDateFormat Throw 'Unparseable Date'?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template