我想知道为什么'Y'会回归2012而'y'会在2011年回归SimpleDateFormat:
System.out.println(new SimpleDateFormat("Y").format(new Date())); // prints 2012
System.out.println(new SimpleDateFormat("y").format(new Date())); // prints 2011
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释原因吗?
我试图解析一个String(YYYY-MM-dd HH:mm)Date,但是错误的日期比预期的错.
码:
Date newDate = null;
String dateTime = "2013-03-18 08:30";
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.ENGLISH);
df.setLenient(false);
try {
newDate = df.parse(dateTime);
} catch (ParseException e) {
throw new InvalidInputException("Invalid date input.");
}
Run Code Online (Sandbox Code Playgroud)
生产:
美国东部时间2012年12月30日08:30(错误)
我试过设置Lenient但没有运气.
更新
感谢Sudhanshu的回答,它帮助我解决了Java转换问题.当我从上面的代码输入返回的日期到数据库时,我正确地得到了日期,但时间总是如此00:00.
ps.setDate(3, new java.sql.Date(app.getDate().getTime()));
Run Code Online (Sandbox Code Playgroud) 我正在尝试将日期转换为字符串,但转换时将2018年更改为2019年。
我尝试了不同的日期,它有效。它仅在2018年12月30日和12月31日失败。
SimpleDateFormat fmt = new SimpleDateFormat("YYYY-MM-dd");
Date date = fmt.parse("2018-12-30");
String date2 = fmt.format(date);
Run Code Online (Sandbox Code Playgroud)
预期结果:2018-12-30
实际结果:2019-12-30