-3

我以"20150119"的形式获取日期,我想将其转换为如下格式:"19. January 2015"

如何以这种格式转换日期。

我尝试了以下代码:

private void convertDate() {
        String m_date = "20150119";
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy.MM.dd");
        try {
            Date date = originalFormat.parse(m_date.toString());
            Log.e("Date is====", date.toLocaleString());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

但它给了我错误:

java.text.ParseException:无法解析的日期:“20150119”(偏移量 8)

4

2 回答 2

2

您将需要指定两种格式:一种用于解析您的输入,一种用于格式化您的输出。

  1. 发生错误是因为您尝试解析的字符串与您在中指定的格式不匹配originalFormat:需要

    SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
    

    如果要解析格式的字符串String m_date = "20150119";。解析具有该格式的字符串将为您提供Date

    Date date = originalFormat.parse(m_date);
    
  2. 然后你可以使用另一种格式来输出你的Date

    SimpleDateFormat outputFormat = new SimpleDateFormat("dd. MMMM yyyy");
    System.out.println("Date: " + outputFormat.format(date));
    
于 2015-05-11T12:57:57.280 回答
1

您正在使用DateFormat

SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy.MM.dd");

所以SimpleDateFormat期待一个String喜欢"2015.01.19"(注意点)。

您正在提供String

String m_date = "20150119";

它不包含点因此SimpleDateFormat无法解析,String因为它不包含点(由您指定)。

要解析你的String,你必须使用

SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");

要打印解析的日期,您必须使用另一个,SimpleDateFormat例如

SimpleDateFormat targetFormat = new SimpleDateFormat("dd. MMMM yyyy");

然后您可以使用该方法format()将您的日期格式化为您想要的格式。

于 2015-05-11T13:03:12.297 回答