概述
利用Java8 时间API https://gitee.com/silenceone/codes/t9oycqzrhue0bfmgw3x8n94
package com.parent.common.utils;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.*;
/**
* @ClassName: Java8DateUtil
* @Description: 日期处理的工具类
* @date: 2016年11月1日 下午6:47:33
*/
public class Java8DateUtil {
private final static ZoneOffset zoneOffset = ZoneOffset.of("+8");
/**
* 把月份划分为周
*
* @param date
* @return
*/
public static Map<Integer, Set<Integer>> getWeekSMonth(int date) {
Map<Integer, Set<Integer>> map = new HashMap<>();
Set<Integer> set = new TreeSet<>();
int first = getFirstDayOfMonth(date);
int last = getLastDayOfWeek(first);
set.add(first);
set.add(last);
map.put(1, set);
//下周就是 last+1
int i = 2;
int next = last + 1;
int lastDayOfMoth = getLastDayOfMonth(date);
while (next <= lastDayOfMoth) {
set = new TreeSet<>();
set.add(next);
int nextLastWeek = getLastDayOfWeek(next);
if (nextLastWeek > lastDayOfMoth) {
set.add(lastDayOfMoth);
} else {
set.add(nextLastWeek);
}
map.put(i, set);
i++;
next = nextLastWeek + 1;
}
return map;
}
/**
* 本月第一天时间戳
*
* @param date
* @return
*/
public static int getFirstDayOfMonth(int date) {
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date, 0, zoneOffset).with(TemporalAdjusters.firstDayOfMonth());
localDateTime = localDateTime.toLocalDate().atStartOfDay();
return (int) localDateTime.toEpochSecond(zoneOffset);
}
/**
* 本月最后一天
*
* @param date
* @return
*/
public static int getLastDayOfMonth(int date) {
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date, 0, zoneOffset).with(TemporalAdjusters.lastDayOfMonth());
localDateTime = localDateTime.toLocalDate().atStartOfDay().plusDays(1).minusSeconds(1);
return (int) localDateTime.toEpochSecond(zoneOffset);
}
/**
* 计算给定日期的星期的第一天(暂时没用到)
*
* @param date
* @return
*/
public static int getFirstDayOfWeek(int date) {
TemporalField fieldISO = WeekFields.of(Locale.CHINA).dayOfWeek();
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date, 0, zoneOffset).with(fieldISO, 1);
localDateTime = localDateTime.toLocalDate().atStartOfDay().plusDays(1);
return (int) localDateTime.toEpochSecond(zoneOffset);
}
/**
* 计算给定日期的星期的最后一天
*
* @param date
* @return
*/
public static int getLastDayOfWeek(int date) {
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date, 0, zoneOffset);
long minusDay = 7 - localDateTime.getDayOfWeek().getValue();
localDateTime = localDateTime.plusDays(minusDay).plusHours(23).plusMinutes(59).plusSeconds(59);
return (int) localDateTime.toEpochSecond(zoneOffset);
}
}
最后
以上就是含糊烧鹅为你收集整理的简单的根据输入时间戳把月份划分为周的全部内容,希望文章能够帮你解决简单的根据输入时间戳把月份划分为周所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复