JAVA 日期工具类:日期获取周,获取指定周周一周日,某月月初月末日期,日期时间戳字符串转换,日期加减等

50 篇文章 2 订阅
23 篇文章 0 订阅

JAVA 日期工具类

  • 获取某天00:00:00点的时间戳
  • 日期获取周
  • 日期获取星期几
  • 获取时间戳属于当月的哪天
  • 获取指定周周一周日
  • 获取某月月初月末日期
  • 根据星期几获取日期
  • 获取年月日,时分秒
  • 根据day获取所在周,周一周日
  • 根据day获取所在月,月初月末日期
  • 根据day获取上月月末的时间戳
  • 日期时间戳字符串转换
  • 日期加减等

源码

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</gr.oupId>
    <artifactId>lombok</artifactId>.1
    <version>1.18.8</version>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/*************************************
 *Class Name: TimeUtils
 *Description: <时间工具类>
 *@author: Seminar
 *@create: 2022/9/15
 *@since 1.0.0
 *************************************/
@Slf4j
public class TimeUtils {

    public static final long ONEDAYMILLIS = 24 * 60 * 60 * 1000;
    public static final String Y_M_D = "yyyy-MM-dd";
    public static final String YMD = "yyyyMMdd";
    public static final String YMDHMS = "yyyy-MM-dd HH:mm:ss.SSS";

    /**
     * 获取当天的00:00:00的时间戳
     *
     * @return
     */
    public static long getBeginMillisOfDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取某天的00:00:00的时间戳
     *
     * @param millis 毫秒时间戳
     * @return
     */
    public static long getBeginMillisOfDay(long millis) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(millis));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取时间戳戳是星期几
     *
     * @param date
     * @return 当前日期是星期几
     */
    public String getWeekOfDate(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
//        log.info("{} {} {} ", cal.get(Calendar.DAY_OF_WEEK), w, weekDays[w]);
        return weekDays[w];
    }

    /**
     * 获取时间戳是星期几
     *
     * @param
     * @return
     */
    public static int getIntWeekOfDate(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(millis));
        return cal.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获取时间戳属于当月的哪天
     *
     * @param millis
     * @return
     */
    public static Integer getDayOfMonth(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(millis));
        int w = cal.get(Calendar.DAY_OF_MONTH);
        return w;
    }


    /**
     * 获取年月日
     *
     * @param epochSecond
     * @return
     */
    public static String getYmd(Long epochSecond) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date(epochSecond));
    }

    /**
     * 获取年月
     *
     * @param millis
     * @return
     */
    public static String getYm(Long millis) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(new Date(millis));
    }

    /**
     * 获取上月月末的时间戳
     *
     * @param epochSecond
     * @return
     */
    public static long getLastMonthMills(Long epochSecond) {
        SimpleDateFormat sdf = new SimpleDateFormat(Y_M_D);
        Calendar cale = Calendar.getInstance();
        if (epochSecond != null && epochSecond != 0L) {
            Date date = new Date();
            date.setTime(epochSecond);
            cale.setTime(date);
        }

        int firstDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最小天数
        cale.set(Calendar.DAY_OF_MONTH, firstDay);//设置日历中月份的最小天数
        return cale.getTimeInMillis() - ONEDAYMILLIS;
    }

    /**
     * 获取某个月的月初日期
     *
     * @param epochSecond
     * @return
     */
    public static String getMonthFirstDay(Long epochSecond) {
        SimpleDateFormat sdf = new SimpleDateFormat(Y_M_D);
        Calendar cale = Calendar.getInstance();
        if (epochSecond != null && epochSecond != 0L) {
            Date date = new Date();
            date.setTime(epochSecond);
            cale.setTime(date);
        }

        int firstDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最小天数
        cale.set(Calendar.DAY_OF_MONTH, firstDay);//设置日历中月份的最小天数
        return sdf.format(cale.getTime());
    }

    /**
     * 获取某个月的月末日期
     *
     * @param epochSecond
     * @return
     */
    public static String getMonthLastDay(Long epochSecond) {
        SimpleDateFormat sdf = new SimpleDateFormat(Y_M_D);
        Calendar cale = Calendar.getInstance();
        if (epochSecond != null && epochSecond != 0L) {
            Date date = new Date();
            date.setTime(epochSecond);
            cale.setTime(date);
        }

        int lastDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        return sdf.format(cale.getTime());
    }

    /**
     * 获取day所在月,月初日期
     *
     * @param day
     * @return
     */
    public static String getMonthFirstDay(String day, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Calendar cale = Calendar.getInstance();
        Date date = sdf.parse(day);
        cale.setTime(date);

        int firstDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最小天数
        cale.set(Calendar.DAY_OF_MONTH, firstDay);//设置日历中月份的最小天数
        return sdf.format(cale.getTime());
    }

    /**
     * 获取day所在月,月末日期
     *
     * @param day
     * @return
     */
    public static String getMonthLastDay(String day, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Calendar cale = Calendar.getInstance();
        Date date = sdf.parse(day);
        cale.setTime(date);
        int lastDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        return sdf.format(cale.getTime());
    }

    /**
     * 根据星期获取日期
     *
     * @param week 星期几 1代码星期日,2代表星期一。。。7代表星期六
     * @return
     */
    public static Date getDateByWeek(int week) {
        int targetWeek = week;
        Calendar c = Calendar.getInstance();
        // 当前日期星期数
        int currWeek = c.get(Calendar.DAY_OF_WEEK);
        do {
            if (currWeek == targetWeek) {
                // 如果所给星期数和当前日期星期数相等则向后推7天
                c.add(Calendar.DAY_OF_MONTH, 7);
            } else if (currWeek < week) {
                currWeek--;
            }
        } while (currWeek != targetWeek);
        return c.getTime();
    }

    /**
     * 根据年月获取月末最后一天日期
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDay(int year, int month, String format) {
        Calendar cale = Calendar.getInstance();

        cale.set(Calendar.YEAR, year);//赋值年份
        cale.set(Calendar.MONTH, month - 1);//赋值月份
        int lastDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        SimpleDateFormat sdf = new SimpleDateFormat(format);    //格式化日期yyyy-MM-dd
        String lastDayOfMonth = sdf.format(cale.getTime());
        return lastDayOfMonth;
    }

    /**
     * 获取某月的第一天
     *
     * @param timeSecs 时间戳13位ms
     * @param format   格式化字符串
     * @return
     */
    public static String getFirstDay(Long timeSecs, String format) {
        Calendar cale = Calendar.getInstance();
        if (timeSecs != null && timeSecs != 0L) {
            Date date = new Date();
            date.setTime(timeSecs);
            cale.setTime(date);
        }
        int lastDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化日期yyyy-MM-dd
        String lastDayOfMonth = sdf.format(cale.getTime());
        return lastDayOfMonth;
    }

    /**
     * 根据年月获取月初第一天日期
     *
     * @param year   年
     * @param month  月
     * @param format 格式化日期
     * @return
     */
    public static String getFirstDay(int year, int month, String format) {
        Calendar cale = Calendar.getInstance();

        cale.set(Calendar.YEAR, year);    //赋值年份
        cale.set(Calendar.MONTH, month - 1);//赋值月份
        int lastDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化日期yyyy-MM-dd
        String lastDayOfMonth = sdf.format(cale.getTime());
        return lastDayOfMonth;
    }

    /**
     * 获取某月的最后一天
     *
     * @param timeSecs 时间戳12位毫秒
     * @param format   格式化日期
     * @return
     */
    public static String getLastDay(Long timeSecs, String format) {
        Calendar cale = Calendar.getInstance();
        if (timeSecs != null && timeSecs != 0L) {
            Date date = new Date();
            date.setTime(timeSecs);
            cale.setTime(date);
        }

        int lastDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);//获取月最大天数
        cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
        SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化日期yyyy-MM-dd
        String lastDayOfMonth = sdf.format(cale.getTime());
        return lastDayOfMonth;
    }

    /**
     * 根据日期获取周
     *
     * @param date
     * @return 45
     */
    public static int getWeek(Date date) {
        GregorianCalendar g = new GregorianCalendar();
        g.setTime(date);
        return g.get(Calendar.WEEK_OF_YEAR); //获得周数
    }

    /**
     * 根据日期获取年+周
     *
     * @param day 20221103
     * @return 202245
     */
    public static String getWeek(String day) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YMD);
        Date date = simpleDateFormat.parse(day);
        GregorianCalendar g = new GregorianCalendar();
        g.setTime(date);
//        g.get(Calendar.WEEK_OF_YEAR); //获得周数
        return day.substring(0, 4) + g.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 日期格式化
     */
    public static String format(Calendar c, String pattern) {
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }
        if (pattern == null || pattern.equals("")) {
            pattern = YMD;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(calendar.getTime());
    }

    /**
     * 获得day所在的周,星期一的日期
     *
     * @param dateStr 年月日
     * @return 根据pattern决定格式
     */
    public static String getWeekFirstDay(String dateStr, String pattern) throws ParseException {
        Calendar strDate = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YMD);
        Date date = simpleDateFormat.parse(dateStr);
        strDate.setTime(date);
        int day = getIntWeekOfDate(strDate.getTimeInMillis());
        strDate.add(Calendar.DATE, -(day - 2));
        return format(strDate, pattern);
    }

    /**
     * 获得day所在的周,星期日的日期
     *
     * @param dateStr 年月日
     * @return 根据pattern决定格式
     */
    public static String getWeekLastDay(String dateStr, String pattern) throws ParseException {
        Calendar strDate = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YMD);
        Date date = simpleDateFormat.parse(dateStr);
        strDate.setTime(date);
        int day = getIntWeekOfDate(strDate.getTimeInMillis());
        strDate.add(Calendar.DATE, 8 - day);
        return format(strDate, pattern);
    }

    /**
     * 获取指定周的第一天
     *
     * @param year 年
     * @param week 月
     * @return
     */
    public static Date getFirstDayOfWeek(int year, int week) {
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置周
        cal.set(Calendar.WEEK_OF_YEAR, week + 1);
        // 设置该周第一天为星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 设置该周第一天为星期一
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);

        return cal.getTime();
    }

    /**
     * 获取指定周的最后一天
     *
     * @param year
     * @param week
     * @return
     */
    public static Date getLastDayOfWeek(int year, int week) {
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置周
        cal.set(Calendar.WEEK_OF_YEAR, week + 1);
        // 设置该周第一天为星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 设置最后一天是星期日
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Sunday
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);

        return cal.getTime();
    }

    public static void main(String[] args) throws ParseException {
        log.info("{} {}", System.currentTimeMillis(), System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000);
        log.info("{} {}", getFirstDay(null, Y_M_D), getLastDay(null, Y_M_D));
        log.info("{} {}", getFirstDay(1668654801114L, Y_M_D), getLastDay(1668654801114L, Y_M_D));
        log.info("{}", DateFormatUtils.format(1668654590343L, Y_M_D));

        log.info("{}", TimeUtils.getLastMonthMills(System.currentTimeMillis()));
        log.info("{} {}", TimeUtils.getMonthFirstDay(System.currentTimeMillis()), TimeUtils.getMonthLastDay(System.currentTimeMillis()));
        log.info("{} {}", TimeUtils.getMonthFirstDay(TimeUtils.getLastMonthMills(System.currentTimeMillis())),
                TimeUtils.getMonthLastDay(TimeUtils.getLastMonthMills(System.currentTimeMillis())));
        log.info("{} {}", getWeek(new Date()), getWeek("20221103"));

        log.info("{} {}", getWeekFirstDay("20221103", YMD), getWeekLastDay("20221105", YMD));
        log.info("{} {}", getWeekFirstDay("20220913", YMD), getWeekLastDay("20220916", YMD));
        log.info("{} {}", getMonthFirstDay("20220913", YMD), getMonthLastDay("20220916", YMD));
        log.info("{} {}", getMonthFirstDay("20221102", YMD), getMonthLastDay("20221105", YMD));

        log.info("{} {}", getFirstDayOfWeek(2022, 52), getLastDayOfWeek(2023, 2));
        log.info("{} {}", getFirstDayOfWeek(2023, 1), getLastDayOfWeek(2023, 2));
        log.info("{} {}", DateFormatUtils.format(getFirstDayOfWeek(2022, 52), YMD), DateFormatUtils.format(getLastDayOfWeek(2023, 2), YMD));
        log.info("{} {}", DateFormatUtils.format(getFirstDayOfWeek(2023, 1), YMD), DateFormatUtils.format(getLastDayOfWeek(2023, 2), YMD));
    }
}
  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Java提供的日期时间类来实现,具体步骤如下: 1. 将日期字符串转换日期对象,可以使用SimpleDateFormat类。 2. 获取当前日期的Calendar对象,可以使用Calendar.getInstance()方法。 3. 将Calendar对象的日期设置为字符串日期所表示的日期,可以使用setTime()方法。 4. 将Calendar对象的日期7天,即可得到下周日期,可以使用add()方法。 5. 判断下周日期是否为周一,如果不是则继续1天,直到下周日期为周一。 6. 将下周日转换字符串,可以使用SimpleDateFormat类。 下面是示例代码: ```java import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class NextMondayExample { public static void main(String[] args) throws Exception { // 日期字符串格式 String dateString = "2022-10-31"; // 将日期字符串转换日期对象 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = dateFormat.parse(dateString); // 获取当前日期的Calendar对象 Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 将日期7天,得到下周日期 calendar.add(Calendar.DAY_OF_MONTH, 7); // 判断下周日期是否为周一,如果不是则继续1天 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); while (dayOfWeek != Calendar.MONDAY) { calendar.add(Calendar.DAY_OF_MONTH, 1); dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); } // 将下周日转换字符串 String nextMonday = dateFormat.format(calendar.getTime()); System.out.println("下周一日期为:" + nextMonday); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛一枚~

您的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值