JAVA中如何从日期时间格式获取星期几?

问题描述 投票:0回答:5

我有这种格式的日期时间信息:

String reportDate="2012-04-19 12:32:24";

我想将一周中的输出日期作为输出(星期四或 4 无论如何结果都很好)。 如何实现这一目标?

谢谢

java dayofweek
5个回答
5
投票

解析字符串后使用

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);

1
投票

使用 SimpleDateFormat 解析

String
然后你就有一个
Date
对象,可以获取星期几。


0
投票

将日期解析为实际的

Date
对象,然后将其传递给 Calendar 实例(通过 setTime(Date date))。然后,您可以使用 DAY_OF_WEEK 获取代表星期几的数字。


0
投票

尝试一下,

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)));

0
投票

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 的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.