get the right Month format date java

爷,独闯天下 提交于 2019-12-20 06:38:43

问题


can any help, how to get the right date from an String like this "2014-01-10T09:41:16.000+0000" my code is:

    String strDate = "2014-01-10T09:41:16.000+0000";
    String day = "";
    String format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    Locale locale = new Locale("es", "ES");
    SimpleDateFormat formater = new SimpleDateFormat(format, locale);
    formater.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

    Calendar cal = Calendar.getInstance();

    try {
        cal.setTimeInMillis(formater.parse(strDate).getTime());
        String offerDate = cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
        System.out.println(offerDate);
    } catch (Exception e){
        System.out.println(e.getMessage());
    }

in the result i give something like this: "10-0-2014", i want the result like that "10-01-2014"

thanks in advance :)


回答1:


The documentation states:

java.util.Calendar.MONTH

MONTH public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

-> Counting starts at 0 for Calendar.MONTH




回答2:


I think the easiest would be to use another formatter object to do the formatting instead of building it yourself:

try {
    Date d = new Date(cal.setTimeInMillis(formater.parse(strDate).getTime()));
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    String offerDate = format.format(d);
    System.out.println(offerDate);
} catch (Exception e){
    System.out.println(e.getMessage());
}


来源:https://stackoverflow.com/questions/21137941/get-the-right-month-format-date-java

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