Home  >  Article  >  Java  >  How Can I Reliably Parse Dates with Varying Formats in Java?

How Can I Reliably Parse Dates with Varying Formats in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 06:48:09567browse

How Can I Reliably Parse Dates with Varying Formats in Java?

Handling Date Parsing with Varying Formats in Java

Introduction:

In Java, parsing strings into dates can be a cumbersome task, especially when dealing with dates in different formats. This article will guide you through a reliable method for parsing dates with varying formats using the SimpleDateFormat class.

Problem:

You're receiving a string representing a date in a specific format (e.g., "dd/MM/yyyy") from a user. However, your application requires the date to be in a different format (e.g., "yyyy-MM-dd").

Solution:

1. Create SimpleDateFormat Objects:

  • Create two SimpleDateFormat objects: fromUser and myFormat.
  • fromUser specifies the input date format (e.g., "dd/MM/yyyy").
  • myFormat specifies the desired output date format (e.g., "yyyy-MM-dd").

2. Parse the Input String:

  • Use the fromUser object to parse the input string and obtain a Date object.

3. Reformat the Date:

  • Convert the parsed Date object into a String representation using the myFormat object.

Example Code:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {
    String inputString = "19/05/2009";
    String reformattedStr = myFormat.format(fromUser.parse(inputString));
    System.out.println(reformattedStr); // Output: 2009-05-19
} catch (ParseException e) {
    e.printStackTrace();
}

Handling Exceptions:

If the input string cannot be parsed or reformatted, a ParseException will be thrown. Handle this exception appropriately within your code.

The above is the detailed content of How Can I Reliably Parse Dates with Varying Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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