37

I have a value like the following Mon Jun 18 00:00:00 IST 2012 and I want to convert this to 18/06/2012

How to convert this?

I tried this method

public String toDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date theDate = null;
        //String in = date + "/" + month + "/" + year;
        try {
            theDate = dateFormat.parse(date.toString());
            System.out.println("Date parsed = " + dateFormat.format(theDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateFormat.format(theDate);
    }

but it throws following exception :

java.text.ParseException: Unparseable date: "Mon Jun 18 00:00:00 IST 2012"

Jagger
  • 10,350
  • 9
  • 51
  • 93
Joe
  • 4,460
  • 19
  • 60
  • 106
  • See related section in this page – jmj Jun 19 '12 at 08:35
  • 2
    @Kazekage Gaara you can see my edit now, let us hope whether you know the answer. – Joe Jun 19 '12 at 08:48
  • 1
    Agree with Tony, instead of voting great comment you people can try to answer if not let others to answer. – Joe Jun 19 '12 at 08:55
  • 1
    possible duplicate of [How to parse a date?](http://stackoverflow.com/questions/999172/how-to-parse-a-date) – Basil Bourque May 03 '15 at 21:23
  • @SAR same issue I am facing please help – Sagar Dec 11 '18 at 09:30
  • @SagarHudge Please check the accepted answer and that really solved my issue – Joe Dec 12 '18 at 10:46
  • Modern comment: This question was asked 10 years ago, and back then we used `Date`. We should not anymore. No matter if having a `Date`, an `Instant`, a `LocalDate` or some other date-time type, there is no need to format to a string and parse back. Also no date-time object holds a format, so formatting into a string is what you need and all you need. If you nevertheless get an old-fashioned `Date`, the modern solution is `date.toInstant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("dd/MM/uuuu")`. – Ole V.V. Nov 20 '22 at 08:49

5 Answers5

85

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    
Rahul Agrawal
  • 8,913
  • 18
  • 47
  • 59
  • 2
    I think the format for the _dateStr_ example should be: SimpleDateFormat("**EEE MMM dd HH:mm:ss z yyyy**") – Pascal Nov 19 '13 at 12:41
  • The code is working fine but it should be z and not Z. – abstractKarshit Jun 23 '16 at 11:49
  • @Pascal i am following same format but not able to parce `("EEE MMM dd HH:mm:ss z yyyy") ` – Sagar Dec 11 '18 at 09:04
  • The OP already had a `Date`. This answer assumes that one is calling `date.toString()` (as in the question) and parses the resulting string back into a `Date`. A needless detour, and error-prone too. Also you shouldn’t "hand format" your date. Use a formatter (nowadays that would be a `DateTimeFormatter`). – Ole V.V. Nov 20 '22 at 08:53
8

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

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 EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


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.

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
6

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}
simo.3792
  • 2,102
  • 1
  • 17
  • 29
Alberto
  • 61
  • 1
  • 1
0

You can also use a formula in excel in order to convert this type of date to a date type excel can read: =DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))

And you get: 12/7/2016 from: Wed Dec 07 00:00:00 UTC 2016

Matan Retzer
  • 65
  • 1
  • 7
-2

A more convenient way will be

try {
            String dateToBeFormatted ="Tue Dec 09 00:00:00 IST 1997";
            
            DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
            DateFormat formatTo = new SimpleDateFormat("MM-dd-YYYY");
            
            Date date = (Date)formatter.parse(dateToBeFormatted);
            String finalDate = formatTo.format(date);
            System.out.println(finalDate);
            
            
        } catch (Exception e) 
        {
            e.printStackTrace();
        }
  • 1
    Thanks for your contribution. I think you are answering a different question. The OP already had a `Date`, so does not need parsing. That said, `Date` and `SimpleDateFormat` are now long outdated and the latter notoriously troublesome, it is never convenient to use it. – Ole V.V. Nov 20 '22 at 08:38
  • Two bugs in your code: (1) When running in my time zone, Europe/Copenhagen, I got `12-08-1997`, one day too early. (2) Upper case `YYYY` is wrong. In this case it gives the expected output. With `Wed Dec 31 00:00:00 CET 1997` I got `12-31-1998`, it is one year off. All in all your answer isn’t so helpful as you had intended it. Allow me to suggest that you either delete it or fix the issues. – Ole V.V. Nov 20 '22 at 09:41