在Java中,我们大多数情况下格式日期都是用的SimpleDateFormat,比如说把一个日期格式成"yyyy-MM-dd"
的形式。
我们要注意的是,对于年份来说,大写的Y和小写的y其意义是不同的。
如JDK的API文档所说的,y是Year、Y是Week Year。至于Week Year是什么,我找到了英文资料:What's the Current Week Number?,其内容如下:
Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week'). The highest week number in a year is either 52 or 53.
大体的意思是说按周计年的第一周是指:以星期一为周始,以星期日为周末,第一个包含该年度四天以上的周。比如2015年按周计年的数据可以看这个网站:Week Numbers for 2015,当然你也可以在这个网站查看其它年份按周计年的数据。
由此我们可以知道,在年始年末时,YYYY(大写)和yyyy(小写)的输出值是不同的。直接上代码最直接,如下代码:
Java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// 2014-12-31
calendar.set(2014, Calendar.DECEMBER, 31);
Date strDate1 = calendar.getTime();
// 2015-01-01
calendar.set(2015, Calendar.JANUARY, 1);
Date strDate2 = calendar.getTime();
// 大写YYYY
DateFormat formatUpperCase = new SimpleDateFormat("YYYY/MM/dd");
System.out.println("2014-12-31 to YYYY/MM/dd: " + formatUpperCase.format(strDate1));
System.out.println("2015-01-01 to YYYY/MM/dd: " + formatUpperCase.format(strDate2));
// 小写YYYY
DateFormat formatLowerCase = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("2014-12-31 to yyyy/MM/dd: " + formatLowerCase.format(strDate1));
System.out.println("2015-01-01 to yyyy/MM/dd: " + formatLowerCase.format(strDate2));
}
}
其结果如下:
2014-12-31 to YYYY/MM/dd: 2015/12/31
2015-01-01 to YYYY/MM/dd: 2015/01/01
2014-12-31 to yyyy/MM/dd: 2014/12/31
2015-01-01 to yyyy/MM/dd: 2015/01/01
转载请注明:宇托的狗窝 » Java时间格式化时YYYY(大写)和yyyy(小写)的区别
我看了JDK的文档,在JDK6之前是不支持大写Y的,JDK7才开始支持。估计你是在JDK6下运行吧。
我把两个JDK的文档的链接放在下面了,你可以参考一下。
JDK6的文档:http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
JDK7的文档:http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html