Search code examples
javadateunixdate-conversion

How to convert String to date using Java in UNIX environment


I am trying to convert a String ("01-OCT-2014") into Date format.

Below is my code for this.

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date d= formatter.parse("01-OCT-2014");
System.out.println("Converted date:"+d);

The above code is working fine in Windows.

But when I am running in Unix environment, it is throwing an exception Unparseable date

Can any one help me out in solving this issue..


Solution

  • I suspect the problem is simply that your Unix environment isn't running in an English locale - so when it tries to parse the month name, it's not recognizing "OCT" as a valid value.

    I would suggest using code like this:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
    Date d = formatter.parse("01-OCT-2014");
    System.out.println("Converted date: " + d);
    

    You might also want to specify the time zone of the formatter - if you're just parsing a date, then using UTC would make sense. Note that your output will use the system local time zone, because you're using Date.toString() - that doesn't mean that the Date has any notion of the time zone in its data; a Date is just a point in time.