将字符串转换为日期并获取 Day

Convert string to date and get Day

如何将字符串日期转换为日期?

我有一个格式为 yyyymmdd 的字符串“20210712”如何将其转换为日期...以及如何获取它的日期。

您可以使用 DateTimeFormatter 和 LocalDate 来完成:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate date = LocalDate.parse("20210712", formatter);
System.out.println(date);
System.out.println(date.getDayOfWeek());
System.out.println(date.getDayOfMonth());
System.out.println(date.getDayOfYear());

输出:

2021-07-12
MONDAY
12
193

您可以使用 String.substr to split the date string into its components. We'll use the + shorthand to convert each component into a number, then create a new Date object from it, using the Date constructor new Date(year, monthIndex, day).

注意:在 JavaScript 中,我们将 monthIndex 传递给日期而不是月份编号,因此 7 月表示为 monthIndex = 6;

要从你的约会对象中获取该月的第几天,你需要 Date.getDate()

要从你的日期中得到星期几,你需要 Date.getDay(),这将 return 0 - 6(星期日 (0) -> 星期六 (6))

要从日期中获取星期几作为字符串,您可以使用 Intl.DateTimeFormat,这将 return 'Monday' -> 'Sunday'.

const timestamp = "20210712";
const year = +timestamp.substr(0,4);
const monthIndex = +timestamp.substr(4,2) - 1;
const day = +timestamp.substr(6,2);

console.log("Timestamp:", timestamp)
console.log("Date components:", JSON.stringify({ year, monthIndex, day }))

const date = new Date(year ,monthIndex, day);
console.log('Date:', date.toDateString());
console.log('Day of Month:', date.getDate());

// Sunday - Saturday : 0 - 6
console.log('Day of Week (0-6):', date.getDay());
console.log('Day of Week (string):', new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(date))