Joh*_*lly 5 java simpledateformat
我试图理解两件事:
SimpleDateFormat不宽松)这是代码
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TestDate {
public static void main(String[] args) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
Date date = format.parse("01/01/13"); // Since this only has a 2 digit year, I would expect an exception to be thrown
System.out.println(date); // Prints Sun Jan 01 00:00:00 GMT 13
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.YEAR)); // Prints 13
}
}
Run Code Online (Sandbox Code Playgroud)
如果有什么不同,我在 Ubuntu 上使用 java 1.6.0_38-b05
简单日期格式 API:
对于解析,如果模式字母的数量超过 2,则无论位数多少,都会按字面解释年份。因此,使用模式“MM/dd/yyyy”,“01/11/12”解析为公元 12 年 1 月 11 日
至于 lenient,当它设置为 false 时,解析会抛出无效日期的异常,例如 01/32/12,而在 lenient 模式下,该日期被视为 02/01/12。SimpleDateFormat内部使用了Calendar,有关宽容的详细信息可以在Calendar API中找到。