LocalDate的简单用法介绍

一、背景

Java8的特性已经不再是“新特性”,很多Java8的类也逐渐被更多的程序员在使用。

但是项目中的日期工具类,有一些还用的是Calandar类,非常不方便。

本文简单给出几个LocalDate的封装,展示一下基本用法。

大家可以多使用Java 8的时间相关类,功能更强大,代码更简洁。

二、上代码

Demo日期工具类


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;

import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;

/**
 * @author 明明如月
 * @date 2018/11/14
 */
public class DateUtil {
    public static DateTimeFormatter defaultDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static DateTimeFormatter simpleDateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static DateTimeFormatter defaultFormatterWithTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * '前一天的日期
     */
    public static LocalDate lastDay(String date, DateTimeFormatter dateTimeFormatter) {
        LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
        return localDate.minusDays(1);
    }

    /**
     * 本周一的日期
     */
    public static LocalDate thisWeekFirstDay(String date, DateTimeFormatter dateTimeFormatter) {
        LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
        return localDate.with(DayOfWeek.MONDAY);
    }

    /**
     * 上周一
     */
    public static LocalDate lastWeekFirstDay(String date, DateTimeFormatter dateTimeFormatter) {
        LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
        return localDate.minusDays(7).with(DayOfWeek.MONDAY);
    }

    /**
     * 本月第一天
     */
    public static LocalDate thisMonthFirstDay(String date, DateTimeFormatter dateTimeFormatter) {
        LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
        return localDate.with(firstDayOfMonth());
    }

    /**
     * 上月第一天
     */
    public static LocalDate lastMonthFirstDay(String date, DateTimeFormatter dateTimeFormatter) {
        LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
        return localDate.minusMonths(1).with(firstDayOfMonth());
    }

    /**
     * 两个时间之间间隔了多少年
     */
    public static BigDecimal year(long low, long high) {
        Instant instant1 = Instant.ofEpochMilli(low);
        Instant instant2 = Instant.ofEpochMilli(high);

        LocalDate localDate1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()).toLocalDate();
        LocalDate localDate2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()).toLocalDate();
        Period period = Period.between(
                localDate1
                , localDate2
        );
        int years = period.getYears();
        int months = period.getMonths();
        BigDecimal monthToYear = new BigDecimal(months).divide(BigDecimal.valueOf(12), 2, RoundingMode.DOWN);
        return BigDecimal.valueOf(years).add(monthToYear);
    }

    /**
     * 是否是同一天
     */
    public static boolean isSameDateByUnixTime(long time1, long time2) {
        LocalDateTime dateTime1 = Instant.ofEpochMilli(time1).atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime dateTime2 = Instant.ofEpochMilli(time2).atZone(ZoneId.systemDefault()).toLocalDateTime();
        return dateTime1.toLocalDate().isEqual(dateTime2.toLocalDate());
    }

}

测试类


import com.chujianyun.common.java8.date.DateUtil;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class DateUtilTest {

    private String today = "2019-05-10";

    private DateTimeFormatter dateTimeFormatter = DateUtil.defaultDateTimeFormatter;

    @Test
    void lastDay() {
        LocalDate localDate = DateUtil.lastDay(today, dateTimeFormatter);
        Assert.assertEquals("2019-05-09", dateTimeFormatter.format(localDate));
    }

    @Test
    void thisWeekFirstDay() {
        LocalDate localDate = DateUtil.thisWeekFirstDay(today, dateTimeFormatter);
        Assert.assertEquals("2019-05-06", dateTimeFormatter.format(localDate));
    }

    @Test
    void lastWeekFirstDay() {
        LocalDate localDate = DateUtil.lastWeekFirstDay(today, dateTimeFormatter);
        Assert.assertEquals("2019-04-29", dateTimeFormatter.format(localDate));
    }

    @Test
    void thisMonthFirstDay() {
        LocalDate localDate = DateUtil.thisMonthFirstDay(today, dateTimeFormatter);
        Assert.assertEquals("2019-05-01", dateTimeFormatter.format(localDate));
    }

    @Test
    void lastMonthFirstDay() {
        LocalDate localDate = DateUtil.lastMonthFirstDay(today, dateTimeFormatter);
        Assert.assertEquals("2019-04-01", dateTimeFormatter.format(localDate));
    }

    @Test
    public void test() throws ParseException {
        // 2018-01-01 --> 1514736000000
        // 2018-01-01 --> 1546272000000

        BigDecimal year = DateUtil.year(1514736000000L, 1546272000000L);
        BigDecimal expect = new BigDecimal(1);
        BigDecimal bigDecimal = expect.setScale(2, BigDecimal.ROUND_HALF_UP);
        Assert.assertEquals(bigDecimal, year);
    }

    @Test
    public void isSameDay() {
        boolean sameDateByUnixTime = DateUtil.isSameDateByUnixTime(1514779260000L, 1514818860000L);
        Assert.assertTrue(sameDateByUnixTime);
    }
}

如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
LocalDateJava 8中的日期类,可以用来表示一个特定的日期,例如年、月、日。它提供了一些方法来获取和操作日期。但是它本身并不能直接用于创建和打印万年历。要实现一个万年历,需要结合LocalDate类和其他相关的类或方法。 根据引用的描述,可以使用LocalDate来计算一个特定日期的星期几。具体步骤是先计算该日期距离一个已知星期几的日期之间的天数差,然后对7取模得到余数,这个余数就代表了该日期的星期几。 要实现一个万年历,可以使用循环来遍历每个日期,并结合LocalDate类的方法来计算星期几。可以从一个已知的日期开始,例如1900年1月1日,然后使用循环递增日期,直到你想要的结束日期。在每个日期上,使用LocalDate类的方法来计算星期几,并将日期和星期几打印出来。这样就可以实现一个简单的万年历。 总结一下,要实现一个万年历,需要使用LocalDate类的方法来计算星期几,并结合循环和其他相关的类或方法来遍历日期并打印出来。具体的实现可以根据需求进行调整和扩展。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [java8 LocalDate 使用详解](https://download.csdn.net/download/weixin_38621897/12742550)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Java打印万年历 两种实现方法](https://blog.csdn.net/qq_43598138/article/details/105972045)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

明明如月学长

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值