How to change the format of date in java [duplicate]

只愿长相守 提交于 2019-12-13 09:04:57

问题


I have a string and i need to convert it to date in the "YYYY-mm-dd" format which i'm unable to do. I checked the similar post on stckoverflow but didnt help so i'm posting this query.

String stringDate = "Dec 13, 2013";

I need this to be convert to Date reportDate = 2013-12-13"; when i use simpledateformat i got unparsable date. Please help


回答1:


Check this out:

    try {
        SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String stringDate = "Dec 13, 2013";

        Date date = format1.parse(stringDate);

        System.out.println(format2.format(date));
    } catch (ParseException exp) {
        // Take appropriate action
    }

Output: 2013-12-13




回答2:


In programming a very important skill is taking information that is close to what you need and using it to find what you do need.

Look at the link in the comments and you can see:

http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

Read that and you have what you need to adjust the answer there to give the results you want.




回答3:


Use SimpleDateFormat as here: new_date is your Date

String stringDate = "Dec 13, 2013";
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD"); 
Date new_date=format.parse(stringDate);



回答4:


String date="Your date";
SimpleDateFormat format = new SimpleDateFormat("MMM DD, YYYY"); 
Date d= format.parse(date);
DateFormat newFormat = new SimpleDateFormat("YYYY-MM-DD");
System.out.println(newFormat.format(d));



回答5:


I would do something like:

SimpleDateFormat parser = new SimpleDateFormat("MMM dd, yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date reportDate = parser.parse(stringDate)
String result = formatter.format(reportDate);


来源:https://stackoverflow.com/questions/21042484/how-to-change-the-format-of-date-in-java

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