Java获取每日、每周、每月、每年各种时间(超详细!)

先引入Hutool-all 工具包 


/*
* 获取本周第一天和最后一天
*
* */
public static List<String> getWeekStartAndEndDay() {
// 获取当前日期
    LocalDate today = LocalDate.now();
    // 获取本周的第一天(周一)
    LocalDate firstDayOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    // 获取本周的最后一天(周日)
    LocalDate lastDayOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    ArrayList<String> strings = new ArrayList<>();
    strings.add(firstDayOfWeek.toString());
    strings.add(lastDayOfWeek.toString());
    return strings;
}
    /*
     * 获取本月第一天和最后一天
     *
     * */
    public static List<String> getMonthStartAndEndDay() {
    // 获取当前日期
    LocalDate currentDate = LocalDate.now();

    // 获取当前月份
    YearMonth currentMonth = YearMonth.from(currentDate);

    // 获取本月的第一天
    LocalDate firstDayOfMonth = currentMonth.atDay(1);

    // 获取本月的最后一天
    LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        ArrayList<String> strings = new ArrayList<>();
        strings.add(firstDayOfMonth.toString());
        strings.add(lastDayOfMonth.toString());
        return strings;

}



    public static String YMDHMSToYMD(String time){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(time, dateTimeFormatter);

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateString = dateTime.format(dateFormatter);
        return dateString;
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值