将 Android 中的日期“2016-06-03”转换为“2016 年 6 月 3 日”

Converting Date "2016-06-03" to "03 JUNE 2016" in Android

我的日期格式为 "2016-06-03",我必须按如下方式转换它:

"03 JUNE 2016".

我试过如下:

 SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
 String newFormat = formatter.format("2016-06-03");

但是,出现以下错误:

Invalid Arguments Exception

请帮我解决这个问题。谢谢。

试试这个转换日期格式的常用函数

public static SimpleDateFormat targetFormat = new SimpleDateFormat();
public static SimpleDateFormat originalFormat = new SimpleDateFormat();
public static String formattedDate = "";

public static String getFormattedDate(String targetPattern,
                                      String existingPattern, String existingValue) {
    formattedDate = existingValue;
    targetFormat.applyPattern(targetPattern);
    DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
    symbols.setAmPmStrings(new String[] { "AM", "PM" });
    targetFormat.setDateFormatSymbols(symbols);
    originalFormat.applyPattern(existingPattern);
    try {
        formattedDate = targetFormat.format(originalFormat
                .parse(existingValue));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return formattedDate;
}

并像

一样使用
 String txtdate = getFormattedDate("dd MMMM yyyy","yyyy-MM-dd","2016-06-03");

您可能想使用 DateFormat 而不是 SimpleDateFormat:

//Should print something like June 27, 2016
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);
String format = df.format(yourDate);

我已经编辑了你的代码,从这里复制它现在工作正常

SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
        String newFormat = null;
        try {
            newFormat = formatter.format(new SimpleDateFormat("yyyy-MM-dd").parse("2016-06-03"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.d("Date", ": " + newFormat); 

输出

D/Date: : 03 June 2016
 public String convert_date(String date)
 {
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
     java.util.Date d = null;
 try 
 {
     d = df.parse(date);
 } catch (ParseException e)
 {
     e.printStackTrace();
 }
     df = new SimpleDateFormat("dd MMMM, yyyy");
     return   df.format(d);
 }

**String convertedDate = convert_date("2016-06-25");**

如果您从 android 中的日历中获取月份,您通常会获取月份编号而不是名称。但是如果你想得到它的名字,你可以通过两种方式得到它。

  1. 获取全名-

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
    String month_name = month_date.format(cal.getTime());
    
  2. 获取月份的简称-

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat month_date = new SimpleDateFormat("MMM");
    String month_name = month_date.format(cal.getTime());
    

有关 SimpleDateFormat class 的更多信息,请查看 - Android Docs .