简体   繁体   中英

Java:Date format conversion issue

I have a date of the format EEE MMM dd HH:mm:ss zzz yyyy

I have to convert this to dd/MM/yyyy

I did the following:

SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat fmtddMMyyyy = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date d = fmt.parse("Mon May 28 00:00:00 IST 2012");<br>
String formattedDate = fmtddMMyyyy.format(d); 

When I tried to print d it displays 0027833001988071567 .

Where am I going wrong?

I have to guess that your real code is only marginally connected to what you show. Due to some experiments and the documentation.

Possibly the original parsing throws an exception and what every you print has nothing to do with you date manipulation.

In order to fix the problem

  • print the string you want to convert
  • print the parsed date
  • print the converted String
  • Use the constructor variants with Locale argument so everybody on stackoverflow can reproduce it, and you application works the same wherever it is running.

All this in a simple class containing nothing but a main method which contains the code.

If the problem persists, come back with the code and its output.

With my advice partially applied you might end with this:

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

public class Experiment {
public static void main(String args[]) throws ParseException {
    SimpleDateFormat fmt = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
    SimpleDateFormat fmtddMMyyyy = new SimpleDateFormat("dd/MM/yyyy",
            Locale.US);
    java.util.Date d = fmt.parse("Mon May 28 00:00:00 IST 2012");
    String formattedDate = fmtddMMyyyy.format(d);
    System.out.println(formattedDate);
}
}

Which prints out

28/05/2012

try:

String formattedDate = fmtddMMyyyy.format(d);

UPD: Well I got the following solution:

SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);

works fine (without locale defining wasn't working for me too). Because you define the month name and day-of-week name according to English language, not your local, as I presume.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM