2

I am getting date in following format, as java string:

Sat Jan 01 00:00:00 CET 2000

i want to convert it to yyyy-MM-dd fromat. For this i am doing:

String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
try{
Date parsed = sdf.parse(strDate);
}catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}

But i am getting exception: Unparseable date: "Sat Jan 01 00:00:00 CET 2001"

Please give me some solution for this.

Thank you

aj_us
  • 119
  • 1
  • 4
  • 8
  • If your locale is not US, see my answer :) – Fortega Oct 06 '10 at 13:44
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 20 '18 at 20:34

8 Answers8

8

The SimpleDateFormat needs to be the input date format, then you can use another SimpleDateFormat to get the appropriate output format, i.e.:

String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
try{
    Date parsed = sdf.parse(strDate);
}
catch(Exception e){
    System.out.println("Exception: " + e.getMessage());
}
System.out.println("Date: " + outputDate.format(parsed));
Lazarus
  • 41,906
  • 4
  • 43
  • 54
  • Hi,String temp = "Sat Jan 01 00:00:00 CET 2000"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd"); Date parsed = null; try{ parsed = sdf.parse(temp); } catch(Exception e){ System.out.println("Exception: " + e.getMessage()); } System.out.println("Date: " + outputDate.format(parsed)); – aj_us Oct 06 '10 at 11:45
  • I think my edit must have passed your comment like ships in the night ;) – Lazarus Oct 06 '10 at 11:46
  • sorry for worng format. I made changes as per your code, i am still getting exception – aj_us Oct 06 '10 at 11:50
  • hi Lazarus, i tried with one 'z' also but still getting exception – aj_us Oct 06 '10 at 12:37
  • This won't compile unless the last System.out.println statement is moved within the try block, but I verified it works. – Greg Case Oct 06 '10 at 13:44
  • @gregcase: it does not work for me, as my locale is nl_BE, and 'Sat' should be 'zat' for me :) – Fortega Oct 06 '10 at 13:46
  • @Fortega SimpleDateFormat has a constructor that accepts a Locale as a second argument, that will allow you to do Locale specific parsing and formatting. – Greg Case Oct 06 '10 at 13:58
  • @gregcase: yup, I know. See my answer :-) @Ajay: does it work for you when you use a Locale.US as second argument when creating the 'sdf' object? – Fortega Oct 06 '10 at 14:09
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 20 '18 at 20:34
4

You need a SimpleDateFormat to parse the existing string and another SimpleDateFormat to format the parsed Date object into the appropriate yyyy-MM-dd string.

You can use applyPattern to change the current pattern in the SimpleDateFormat so you don't have to create a new object.

I'll leave the patterns as an exercise for the student.

tKe
  • 560
  • 2
  • 9
3

You are trying to parse the date with the format "yyyy-MM-dd".

You need to build a SimpleDateFormat matching the format you need to parse, then use the one in your snippet to format it.

The parse format you need will be something along the lines of "EEE MMM dd HH:mm:ss z yyyy".

brabster
  • 42,504
  • 27
  • 146
  • 186
1

Your pattern needs to match the date you are parsing, something like this: Look at the SimpleDateFormat doc for complete instructions.

SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd hh:mm:ss zzz yyyy");
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
1

If your locale is not US or another english language locale, you will get an exception, because Sat is not known, so you should specify the locale in your input format.

Try this:

String dateAsString = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date: " + outputFormat.format(inputFormat.parse(dateAsString)));

ps: Jan 01 2001 is not a Saturday :)

Fortega
  • 19,463
  • 14
  • 75
  • 113
1

tl;dr

After fixing your faulty input text, this value can be parsed using the modern java.time classes.

ZonedDateTime.parse( 
    "Mon Jan 01 00:00:00 CET 2001"    // Changed incorrect "Sat" to correct "Mon". 
    ,
    DateTimeFormatter.ofPattern( 
        "EEE MMM dd HH:mm:ss z uuuu" 
        , 
        Locale.US                     // Specify a `Locale` to determine human language and cultural norms used in translation.
    )                                 // Returns a `DateTimeFormatter` object to be passed as second argument to `parse` method.
)                                     // Returns a `ZonedDateTime` object.
.toString()                           // Generates a `String` using standard ISO 8601 format extended by appending zone name in square brackets.

2001-01-01T00:00+01:00[Europe/Paris]

Wrong input

Your example input string "Sat Jan 01 00:00:00 CET 2001" is incorrect. January 1, 2001 was a Monday, not a Saturday. See calendar display.

Furthermore, early in your Question you use the year 2000, while later you use 2001.

Details

The Answer by Lazarus is correct, but uses now-outmoded classes. It is correct in that your formatting pattern failed to match the input string.

First we must fix your faulty input string, changing "Sat" to be "Mon".

String input = "Mon Jan 01 00:00:00 CET 2001";  // After altering the original input string, fixing "Sat" to be "Mon".

Use only java.time classes for your date-time work. These replace Date & Calendar etc.

Define a formatting pattern to match your input string. Specify a Locale to determine the human language and cultural norms used in translating from the input string.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f  );

Generate a String in standard ISO 8601 format extended by appending the name of the time zone in square brackets.

String output = zdt.toString() ;

System.out.println(output);

2001-01-01T00:00+01:00[Europe/Paris]

To see the same moment in UTC, extract a Instant.

Instant instant = zdt.toInstant() ;

instant.toString(): 2000-12-31T23:00:00Z

Tips

  • Your input string uses a terrible format. Always use standard ISO 8601 formats for exchanging date-time values as text.
  • Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as CET, EST, or IST as they are not true time zones, not standardized, and not even unique(!).

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

What Date class are you using? If you're using an IDE, it's easy to accidentally use java.sql.Date instead of java.util.Date by accident. Here's my complete sample program and its output:

package pkg;

import java.lang.String;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Foo
{
    public static void main(String[] args) throws Exception
    {
        Date parsed = null;
        String strDate = "Sat Jan 01 00:00:00 CET 2001";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
        try{
            parsed = sdf.parse(strDate);
        }
        catch(Exception e){
            System.out.println("Exception: " + e.getMessage());
        }
        System.out.println("Date: " + outputDate.format(parsed));
    }
}

produced

Date: 2000-12-31

which is correct, as I'm in EST, unless I'm mistaken about where CET is. No exceptions encountered, of the parsing kind or otherwise.

Pops
  • 30,199
  • 37
  • 136
  • 151
0

I have a issue where I need to convert a date in the format of String to another string but with different format.

E.g. - "2022-05-16" convert it into "05/16/2022" i.e. "yyyy-MM-dd" to "MM/dd/yyyy".

Whenever you convert a date string from one form to another, you cannot do it directly.

First convert the string into given format and create a date object.

And then from the date object you can convert it to the format you are looking for.

Here is the code example:

public static String convertDate(String providedDate, String providedDateFormat, String finalConversionDateFormat){
    StringBuffer tempStr = new StringBuffer();
    
    //Create the SimpleDateFormat object for specific formats
    SimpleDateFormat existingDateFormat = new SimpleDateFormat(providedDateFormat);
    SimpleDateFormat sdf = new SimpleDateFormat(finalConversionDateFormat);
    
    try {
        //Convert the provided date into Date object with the given format.
        Date tempDate = existingDateFormat.parse(providedDate);
        
        //Once the existing date object created, convert into format whatever you are looking for
        tempStr.append(sdf.format(tempDate));
        
    } catch (java.text.ParseException e) {
        //logger.error(e);
    }
    return tempStr.toString();
}

convertDate("2022-05-16", "yyyy-MM-dd", "MM/dd/yyyy");

Atul
  • 3,043
  • 27
  • 39
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Please see [the good answer by Basil Bourque](https://stackoverflow.com/a/50439100/5772882). – Ole V.V. May 16 '22 at 11:03
  • @OleV.V. ... Yes you are right but sometimes you need to maintain some code which is still in production. It is just to demonstrate that how the things works rather that to solve the problem. – Atul May 16 '22 at 11:52
  • If I were to maintain your code, I would start by rewriting it to use java.time. It worries me that future readers may here find a wall of answers using and advising the use of bad old classes and thinking they should do the same when the truth is they definitely should not. – Ole V.V. May 16 '22 at 12:23