Format Date Java

ε祈祈猫儿з 提交于 2019-12-10 18:40:05

问题


How to format a string that looks like this

Sat Dec 08 00:00:00 JST 2012

into yyyy-mm-dd i.e.

2012-12-08

From browsing the web, I found this piece of code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    String dateInString = "Sat Dec 08 00:00:00 JST 2012";

    try {

        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatter.format(date));

    } catch (ParseException e) {
        e.printStackTrace();
    }

However, I am unable to modify it to accept the first line (Sat Dec 08 00:00:00 JST 2012) as a string and format that into the yyyy-mm-dd format.

What should I do about this? Should I be attempting to modify this? Or try another approach altogether?

Update: I'm using this from your answers (getting error: Unparseable date: "Sat Dec 08 00:00:00 JST 2012")

public static void main(String[] args) throws ParseException{
        SimpleDateFormat srcFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.JAPANESE);
        SimpleDateFormat destFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.JAPANESE);
        Date date = srcFormatter.parse("Sat Dec 08 00:00:00 JST 2012");
        String destDateString = destFormatter.format(date);
       /* String dateInString = "Sat Dec 08 00:00:00 JST 2012";*/
        System.out.println(destDateString);

        /*try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }*/
    }
}

回答1:


SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String dateInString = "Wed Oct 16 00:00:00 CEST 2013";
    try {
        SimpleDateFormat parse = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
        Date date = parse.parse(dateInString);
        System.out.println(date);
        System.out.println(formatter.format(date));

    } catch (ParseException e) {
        e.printStackTrace();
    }

Change your formation to this new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

Thanks..




回答2:


Try this -

SimpleDateFormat srcFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.JAPANESE);
SimpleDateFormat destFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.JAPANESE);
Date date = srcFormatter.parse("Sat Dec 08 00:00:00 JST 2012");
String destDateString = destFormatter.format(date);



回答3:


You need two SimpleDateFormat objects. One to parse the date from the string using parse() method and the second one to output it in desired format using format() method. For more info about date formatting check the docs.



来源:https://stackoverflow.com/questions/22323837/format-date-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!