我有这种格式的日期时间信息:
String reportDate="2012-04-19 12:32:24";
我想将一周中的输出日期作为输出(星期四或 4 无论如何结果都很好)。 如何实现这一目标?
谢谢
解析字符串后使用
Calendar
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Date d = sdf.parse(reportDate);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal.get(Calendar.DAY_OF_WEEK);
尝试一下,
System.out.println(new SimpleDateFormat("E").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportDate)));
System.out.println(new SimpleDateFormat("F").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportDate)));
java.time
2014 年 3 月,Java 8 引入了
java.time
,现代日期时间 API,取代了容易出错的遗留、java.util
日期时间 API。
此答案中使用的步骤:
LocalDateTime
将给定的日期时间字符串解析为 DateTimeFormatter
实例。然后,从生成的 LocalDateTime
对象中获取所需的值。
演示:
public class Main {
public static void main(String[] args) {
String reportDate="2012-04-19 12:32:24";
DateTimeFormatter parsingPattern = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(reportDate, parsingPattern);
System.out.println(ldt.getDayOfWeek()); // THURSDAY
System.out.println(ldt.getDayOfWeek().getValue()); // 4
}
}
输出:
THURSDAY
4
从 Trail:日期时间了解有关现代日期时间 API 的更多信息。