Problem converting date format in Java

后端 未结 6 1797
余生分开走
余生分开走 2021-01-21 11:58

I have a string in the form MMM/dd/yyyy, ie. May/21/2010. Now I want to convert it to yyyyMMdd, ie. 20100521.

My code is:

public static void main(String[         


        
6条回答
  •  逝去的感伤
    2021-01-21 12:35

    You will need to apply the locale on SimpleDateFormat.

    Here's a more shorter version:-

    public String transformPrevDate(String date) {
        DateFormat oldFormat = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
        DateFormat newFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
    
        String formattedDate = "";
    
        try {
            formattedDate = newFormat.format(oldFormat.parse(date));
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
    
        return formattedDate;
    }
    
    @Test
    public void testTransformPrevDate() {
        assertEquals("20110113", transformPrevDate("Jan/13/2011"));
        assertEquals("20010203", transformPrevDate("Feb/03/2001"));
    }
    

提交回复
热议问题