peter sze
peter sze

Reputation: 3

converting a string to date in Java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TesterA
{
    public static void main(String[] args)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        String dateInString = "7-Jun-2013";

        try
        {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    }
}

I was trying to run this sample code copy from a web, but it doesn't work. How should I change it?

This is the error I got

java.text.ParseException: Unparseable date: "7-Jun-2013"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at TesterA.main(TesterA.java:14)

Upvotes: 0

Views: 2210

Answers (2)

user3453226
user3453226

Reputation:

java.text.ParseException means you provided a string which cannot be parsed using the current settings.

Just set the Locale.

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

Upvotes: 0

Jens
Jens

Reputation: 69505

I think it is a problem with your locale.

Try:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

Upvotes: 1

Related Questions