java获取当天是周几
方式说明
- 用Calendar#DAY_OF_WEEK 来获取
- 用SimpleDateFormat 的
u
周标识,格式化日期来获取 - 用LocalDate.getDayOfWeek() 来获取
代码实现
package com.example.demo.util.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/** * 获得当前周几 */
public class DateUtils {
public static void main(String[] args) throws ParseException {
getWeekFromStrDateByCalendar("2021-03-28");
getWeekFormStrDateByFormat("2021-03-28");
getWeekFromStrDateByLocalDate("2021-03-28");
}
static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/** * @see java.util.Calendar#DAY_OF_WEEK * @see java.util.Calendar#SUNDAY * Calendar 对象中 周日开始的 标识 1, 周六 标识 7 * 将对象转为 Calendar 对象,在用该对象的 get 方法,带入指定字段获取 对应的 值 (DAY_OF_WEEK) * @param str * @throws ParseException */
public static void getWeekFromStrDateByCalendar(String str) throws ParseException {
Date parse = simpleDateFormat.parse(str);
Calendar instance = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("Asia/Shanghai")));
instance.setTime(parse);
int i = instance.get(Calendar.DAY_OF_WEEK);
System.out.println(i);
}
/** * 根据 SimpleDateFormat 对象的 说明,提示,发送 周几 对应的格式符 为 'u' * @param str * @throws ParseException */
public static void getWeekFormStrDateByFormat(String str) throws ParseException {
Date parse = simpleDateFormat.parse(str);
// u 指定周几
SimpleDateFormat format = new SimpleDateFormat("u");
String format1 = format.format(parse);
System.out.println(format1);
}
/** * @param str * @throws ParseException */
public static void getWeekFromStrDateByLocalDate(String str) throws ParseException {
LocalDate parse = LocalDate.parse(str, formatter);
DayOfWeek dayOfWeek = parse.getDayOfWeek();
System.out.println(dayOfWeek.toString());
System.out.println(dayOfWeek.get(ChronoField.DAY_OF_WEEK));
}
}
还没有评论,来说两句吧...