【发布时间】:2016-06-23 23:08:33
【问题描述】:
这是我的日期字符串“Thu Feb 25 12:58:28 MST 2016”,我使用这个格式“E MMM dd HH:mm:ss Z yyyy”进行解析。
但我收到日期解析错误。
我该怎么办?
我正在使用以下函数解析日期字符串
public static String getDate(String targrtDate) {
String dateStr = targrtDate;
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
if (date == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
String formatedTime = cal.get(Calendar.HOUR) + "/" + cal.get(Calendar.MINUTE);
Log.i("formatedDate", "" + formatedDate + " " + formatedTime);
return formatedDate;
}
【问题讨论】:
-
您使用的代码运行良好。只需从 java.util.Date 导入 Date 类。如果你从 import java.sql.Date 导入日期类,那么你会得到异常。只需从 java.sql.Date 导入 Date 类。
-
是的,我导入了你告诉我的同一个类,但是如果我使用 Thu Feb 25 12:58:28 GMT 2016,那么工作正常,但是当我使用 MST 作为时区时,它会给出解析错误。跨度>
-
MST时区的解决方法是什么?
-
我刚刚更改了您的代码 SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");它工作正常我已经测试了日期“Thu Feb 25 12:58:28 MST 2016”一旦检查这个
-
为了安全起见,您应该使用
new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy", Locale.US);,因为您的模式对区域设置敏感,并且您的默认区域设置可能不是英语。
标签: android datetime calendar simpledateformat