将日期14 8月2011更改为格式20110814 ..我怎么能在java中这样做?
这里14aug是一个字符串... String date ="14aug";
Boz*_*zho 24
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);
Run Code Online (Sandbox Code Playgroud)
参考: java.text.SimpleDateFormat
更新:The Elite Gentleman的问题非常重要.如果以a开头,String则应首先解析它以date从上面的示例中获取对象:
Date date = new SimpleDateFormat("dd MMM yyyy").parse(dateString);
Run Code Online (Sandbox Code Playgroud)
其他答案在 2011 年写的时候都是很好的答案。时间在前进。今天没有人应该使用现在已经过时的类SimpleDateFormat和Date. 现代答案使用以下java.time类:
String date = "14 aug 2011";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd MMM uuuu")
.toFormatter(Locale.ENGLISH);
System.out.println(LocalDate.parse(date, parseFormatter)
.format(DateTimeFormatter.BASIC_ISO_DATE));
Run Code Online (Sandbox Code Playgroud)
这将打印所需的:
20110814
Run Code Online (Sandbox Code Playgroud)
现代的解析机制有些严格,因为经验表明旧的解析机制过于宽松,并且经常在人们预期会出现错误消息的情况下产生令人惊讶的结果。例如,现代要求正确的大小写,即英文中的大写字母 A,除非我们告诉它解析时不区分大小写。所以这就是我对parseCaseInsensitive(). 呼叫会影响下面的建设者方法调用,所以我们必须把它之前 appendPattern()。
编辑:"14aug"从字面上从问题中取出你的字符串。SimpleDateFormat将使用 1970 作为默认年份(纪元的年份),给您带来如何获得正确年份的麻烦。现代类允许您明确指定默认年份,例如:
String date = "14aug";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("ddMMM")
.parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
.toFormatter(Locale.ENGLISH);
Run Code Online (Sandbox Code Playgroud)
有了这个改变,今天运行代码我们得到:
20170814
Run Code Online (Sandbox Code Playgroud)
编辑 2:现在使用Basil Bourque's answer 中DateTimeFormatter.BASIC_ISO_DATE推荐的格式。