我想知道为什么'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) 我正在尝试使用parse函数SimpleDateFormat将a String转换为aDate
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
String strInput1 = "29-04-2014";
System.out.println("string 1: " + strInput1);
Date date1 = new Date();
try {
date1 = sdf.parse(strInput1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 1: " + date1.toString());
String strInput2 = sdf.format(date1);
System.out.println("string 2: " +strInput2);
Date date2 = new Date();
try {
date2 = sdf.parse(strInput2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 2 " …Run Code Online (Sandbox Code Playgroud) 这是代码:
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1451438792953L), ZoneId.of("UTC"));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");
String output = dateTimeFormatter.format(localDateTime);
Run Code Online (Sandbox Code Playgroud)
这是值localDateTime:
2015-12-30T01:26:32.953
Run Code Online (Sandbox Code Playgroud)
这是值output:
2016-12-30T01:26:32.953Z
Run Code Online (Sandbox Code Playgroud)
为什么要增加一年?
其中java.time.temporal.WeekFields有几种方法,有时会newYearWeek增加年数1。为什么?
这是一个奇怪的错误。