简体   繁体   English

SimpleDateFormat中行为的解释

[英]explanation for behavior from SimpleDateFormat

Try this: 尝试这个:

DateFormat df = new SimpleDateFormat("y");
System.out.println(df.format(new Date()));

Without reading the javadoc for SimpleDateFormat, what would you expect this to output? 如果不阅读SimpleDateFormat的javadoc,您期望它输出什么? My expectation was "0". 我的期望是“ 0”。 That is to say, the last digit of the current year, which is 2010. 也就是说,本年的最后一位数字是2010。

Instead it pads it out to 2 digits, just as if the format string had been "yy". 而是将其填充为两位数,就像格式字符串为“ yy”一样。

Why? 为什么? Seems rather bizarre. 似乎很奇怪。 If I had wanted 2 digits then I'd have used "yy". 如果我想要2位数字,那么我会使用“ yy”。

"Without reading the javadoc" is a dangerous attitude more often than not. “不阅读Javadoc”常常是一种危险的态度。 Joshua Bloch wrote a book on this strange behaviours in Java. 约书亚·布洛赫 Joshua Bloch )就 Java中的这种奇怪行为写了一本书

That's why you need to check the documentation : 因此,您需要检查文档

For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century. 要使用缩写的年份模式(“ y”或“ yy”)进行分析,SimpleDateFormat必须解释相对于某个世纪的缩写的年份。

"y" is an abbreviation, so this is expected behavior. “ y”是缩写,因此这是预期的行为。

If you want only a digit you can: 如果只想要一个数字,则可以:

System.out.println(df.format(new Date()).substring(1));

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM