Android中的日期格式

问题描述 投票:0回答:4

我有一个问题,我想以'2013年11月15日'格式解析字符串为Date,但是我无法在SimpleDateFormat类中使用MMMM D,YYYY来做到这一点。请就此提出任何解决方案。

代码:

SimpleDateFormat formatter = new SimpleDateFormat("MMMM DD, yyyy");
try {
    Date publishedDate = formatter.parse(pictureDirectory.replace(str, ""));
    hashMap.put(publishedDate, getImageFromSdCard(picturePath));
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

它总是返回'IST 2013年11月15日星期五00:00:00'。

android simpledateformat
4个回答
1
投票

[在SimpleDateFormat处查看Android中的示例。

String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

输出:

                 yyyy-MM-dd 1969-12-31
                 yyyy-MM-dd 1970-01-01
           yyyy-MM-dd HH:mm 1969-12-31 16:00
           yyyy-MM-dd HH:mm 1970-01-01 00:00
          yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
          yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
   yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
   yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
 yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
 yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000

0
投票

您可以做这样的事情

SimpleDateFormat orignalFormat= new SimpleDateFormat("MMMMMMMMM dd, yyyy"); //November 15, 2013
            Date date = null;
            try {
                    date = origFormat.parse(apkgalaxy.getPosted_on());              
            } catch (ParseException e) {
                e.printStackTrace();
            }

并通过以下代码将日期设置为所需格式

SimpleDateFormat newFormat_date= new SimpleDateFormat("yyyy-MM-dd"); //any format you want
                if (date!=null) {
                    String desiredDateFormat = newFormat_date.format(date);
                    holder.posted_on_date.setText(desiredDateFormat);
                }else{
                    holder.posted_on_date.setText("N/A");
                }

0
投票

我认为您不应该使用可变对象(例如Date)作为HashMap的键。考虑将日期转换为字符串。这就是我格式化日期的方式。

DateFormat formatter1 = new SimpleDateFormat("MMMMM DD, yyyy");
System.out.println(formatter1.parse("15/02/2013"));

0
投票

由于SimpleDateFormat被弃用

我建议您使用这种方式

android.text.format.DateFormat dateFormat= new android.text.format.DateFormat();
dateFormat.format("MMMM DD, yyyy", new java.util.Date());
© www.soinside.com 2019 - 2024. All rights reserved.