Problem converting date format in Java

后端 未结 6 1782
余生分开走
余生分开走 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:17

    SimpleDateFormat uses your locale - so your computer is probably set to use Danish by default. Specify the English Locale explicitly:

    DateFormat formatter = new SimpleDateFormat("MMM", Locale.ENGLISH);
    
    0 讨论(0)
  • 2021-01-21 12:22

    Use SimpleDateFormat(String pattern, Locale locale) to add Locale to your date parsing (for english, use Locale.ENGLISH).

    Better solution:

    public String transformPrevDate(String datoe) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
    
        try {
            return dateFormat2.format(dateFormat.parse(datoe));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2021-01-21 12:27

    Your transformDate method can be much simpler written like this:

    DateFormat input = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
    DateFormat output = new SimpleDateFormat("yyyyMMdd");
    public String transformPrevDate(String datoe) throws ParseException {
        return output.format(input.parse(datoe));
    }
    

    You don't need to do your parsing yourself.

    0 讨论(0)
  • 2021-01-21 12:34

    use SimpleDateFormat(String pattern, Locale locale);

    0 讨论(0)
  • 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"));
    }
    
    0 讨论(0)
  • 2021-01-21 12:38

    SimpleDateFormat is locale-dependent, and it's using your own locale by default. If you would like to use an English-based locale, you can create it by passing in a Locale when you create your SimpleDateFormat.

    So to use a US-based locale, change your SimpleDateFormat initialization to:

        DateFormat formatter = new SimpleDateFormat("MMM", Locale.US);
        DateFormat formatter2 = new SimpleDateFormat("MM", Locale.US);
    
    0 讨论(0)
提交回复
热议问题