我需要将日期(2011-Jan-01)转换为任何simpledateformats格式。
eclipse设计器使用Java 7。
String pDate = obj.getJSONArray("product").getJSONObject(i).getString("createdDate");
//"2011-Jan-01" - date format.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
Date fDate = format.parse(pDate);
System.out.println("jsonDate: " + fDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("pDate: " + pDate);//"2011-Jan-01"
errors:
error:java.text.ParseException:Unparseable date:"2011-Jan-01"
error: at java.text.DateFormat.parse(DateFormat.java:348)
我在上面遇到错误。
答案 0 :(得分:2)
您的解析格式不应包含时间(因为您的输入仅是日期),并且您需要另一个格式调用来生成所需的输出。像
String pDate = "2011-Jan-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd");
try {
Date fDate = format.parse(pDate);
System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(fDate));
} catch (ParseException e) {
e.printStackTrace();
}
输出
01-01-2011
答案 1 :(得分:1)
这在Java 7上有效(详情如下):
DateTimeFormatter jsonDateFormatter = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String pDate = "2011-Jan-01";
LocalDate fDate = LocalDate.parse(pDate, jsonDateFormatter);
pDate = fDate.format(outputDateFormatter);
System.out.println("Formatted date: " + pDate);
摘要的输出是:
格式化日期:2011年1月1日
除非您有充分的理由不这样做,否则建议您对用户的语言环境使用Java的一种内置格式,而不要对输出格式进行硬编码。例如:
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.UK);
现在输出为:
格式化日期:2011年1月1日
您试图在问题中使用的旧日期时间类Date
和SimpleDateFormat
的设计很差,众所周知,后者很麻烦。幸运的是,它们也早已过时。现代的Java日期和时间API java.time更好用。
是的,java.time在Java 7上运行良好。它至少需要 Java 6 。
org.threeten.bp
导入日期和时间类。java.time
。java.time
向Java 6和7(JSR-310的ThreeTen)的反向端口。答案 2 :(得分:0)
将SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
更改为SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd");