package com.opensesame.budget.utils;
import com.opensesame.core.util.DateUtils;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 周工具类
*/
public class weekUtils {
//获得当前日期属于今年的第几周
public static Integer getWeek(Long time) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
calendar.setTimeInMillis(time);//获得时间戳
int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);//获得当前日期属于今年的第几周
return weekOfYear;
}
//一年有多少周
public static Integer getWeekCount(Long year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Math.toIntExact(year), 2, 5);
calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
// calendar.setTimeInMillis(time);//获得时间戳
int weeksInWeekYear = calendar.getWeeksInWeekYear();
return weeksInWeekYear;
}
/**
* @return
* @MethodName 日期转换成星期
* @Description TODO
* @Param 日期(yyyy-MM-dd)
* @Date 2019/12/4 12:29
* @Created by 石昌鹏
*/
public static String dateToWeek(String datetime) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance(); // 获得一个日历
Date datet = null;
try {
datet = f.parse(datetime);
cal.setTime(datet);
} catch (Exception e) {
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 获取本年度最后一天
*/
public static Long getYearEnd(Long year) {
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, Math.toIntExact(year));
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 获取本周最后一天最后一秒
*/
public static Long getWeekend() {
Calendar cal = Calendar.getInstance();
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
cal.add(Calendar.DATE, 6);
return DateUtils.getEndTimeOfDay(cal.getTimeInMillis());
}
/**
* 获取本周每一天当前时间的时间戳
*/
public static List<Long> getNowThisWeek() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd E");
List<Long> re = new ArrayList<>();
for (Date date : getWeekDay()) {
System.out.println(date.getTime());
re.add(date.getTime());
}
return re;
}
public static Date[] getWeekDay() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
Date[] dates = new Date[7];
for (int i = 0; i < 7; i++) {
dates[i] = calendar.getTime();
calendar.add(Calendar.DATE, 1);
}
return dates;
}
}