-2

I want to format date to string in "EEE, d MMM YYYY HH:mm:ss z" but not able to receive desired output.

I referred this tutorial however it not working as per expectation , see code below :

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class MyClass {
    public static void main(String args[]) {

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM YYYY HH:mm:ss z");
        //tried this as well  new SimpleDateFormat("EEE',' d MMM YYYY HH:mm:ss z",Locale.US);
        String strDate = date.toString();
        System.out.println(strDate);// Tue Sep 19 10:31:40 GMT 2017
        // i want this --> Tue, Sep 19 2017 10:31:40 GMT 

    }
}

Please find jdoodle link for working example Appreciate your help !

Ankit
  • 5,733
  • 2
  • 22
  • 23
  • 1
    And why do you expect to get the correct format when you don't even use the formatter? – Tom Sep 19 '17 at 10:49
  • I realise the mistake i made , i am fairly new to java , thanks for your responses. – Ankit Sep 19 '17 at 10:55
  • 1
    You should try to use an IDE like Netbeans, Eclipse or IntelliJ IDEA. They would tell you that `formatter` is currently unused and make it easier to detect such issues in an instant. – Tom Sep 19 '17 at 10:58
  • 1
    Possible duplicate of [Getting Date in HTTP format in Java](https://stackoverflow.com/questions/7707555/getting-date-in-http-format-in-java). That question is specifically about the same format. The format is also known as RFC 1123 or HTTP format. – Ole V.V. Sep 19 '17 at 12:38
  • 1
    I always recommend throwing out the long outdated classes `Date` and `SimpleDateFormat` and using the modern Java date and time API instead. I do particularly in this case since the modern API includes a built-in formatter that gives you exactly what you want: [`DateTimeFormatter.RFC_1123_DATE_TIME`](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#RFC_1123_DATE_TIME). There’s more in [this answer](https://stackoverflow.com/a/26367834/5772882). – Ole V.V. Sep 19 '17 at 12:41

1 Answers1

1

You created a DateFormat, but the you didn't use it. Change

String strDate = date.toString();

to

String strDate = formatter.format(date);
Leo Aso
  • 11,898
  • 3
  • 25
  • 46