超级全的时间处理工具类

@最近项目中遇到一些需要对当前时间进行处理的数据,所以就写了一些处理时间数据的方法,与各位程序员分享


说明:yyyyMMdd---->20200807---->2020年8月8日。 yyyyWW---->202031---->2020年第31周


根据时间yyyyMMdd,返回yyyyWW(W代表周)

public static String getYearWeekByDay(String day) {
DateTimeFormatter format = DateTimeFormat.forPattern(“yyyyMMdd”);
DateTime dateTime = DateTime.parse(day, format);
int week = dateTime.getWeekOfWeekyear();
String weekStr = week + “”;
if (week < 10) {
weekStr = “0” + week;
}
return dateTime.getWeekyear() + weekStr;
}

根据日期,返回当前该周最后一天

public static Integer getLastDayByWeek(int weekNo) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Integer.valueOf(String.valueOf(weekNo).substring(0, 4)));
calendar.set(Calendar.WEEK_OF_YEAR, Integer.valueOf(String.valueOf(weekNo).substring(4)) + 1);
calendar.set(Calendar.DAY_OF_WEEK, 1);
DateFormat fmtDateTime = new SimpleDateFormat(“yyyyMMdd”);
return Integer.parseInt(fmtDateTime.format(calendar.getTime()));
}

根据周,返回上周的最后一天

public static Integer getLastDayByYearWeek(String weekNo) {
Integer year = Integer.parseInt(weekNo.substring(0, 4));
Integer week = Integer.parseInt(weekNo.substring(4, 6));
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
// calendar.setMinimalDaysInFirstWeek(7);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 8);
Date start = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMMdd”);
System.out.println(sdf.format(start));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date end = calendar.getTime();
return Integer.parseInt(sdf.format(end));
}

指定日期向后推多少天,返回后推的每一天

public static String[] getOneGroupDays(String dayNO, int number) {
DateTimeFormatter day = DateTimeFormat.forPattern(“yyyyMMdd”);
String days[] = new String[number];
for (int i = 0; i < number; i++) {
DateTime dateTime = DateTime.parse(dayNO, day).minusDays(i);
days[i] = dateTime.toString(day);
}
return days;
}

指定日期向后推多少周,返回后推的每一周

public static String[] getOneGroupWeeks(String weekNo, int number) {
DateTimeFormatter week = DateTimeFormat.forPattern(“yyyyww”);
String weeks[] = new String[number];
for (int i = 0; i < number; i++) {
DateTime dateWeek = DateTime.parse(weekNo, week).minusWeeks(i);
weeks[i] = dateWeek.toString(week);
}
return weeks;
}

你可能感兴趣的:(工具类,java)