LocalDate、LocalTime、LocalDateTime的一些基本用法

1.LocalDate的基本用法

@Test
    public void testLocalDate() {
        //获取当前日期
        LocalDate localDate = LocalDate.now();
        System.out.println("获取当前日期:" + localDate);
        //自行构造日期
        LocalDate localDate1 = LocalDate.of(2020, 12, 9);
        System.out.println("自行构造日期:" + localDate1);
        //获取某日期的年
        System.out.println("获取某日期的年:" + localDate.getYear());
        //获取某日期的月(int)
        System.out.println("获取某日期的月(int):" + localDate.getMonthValue());
        //获取某日期的月(字符串)
        System.out.println("获取某日期的月(字符串):" + localDate.getMonth());
        //获取某日期的在月份中的天
        System.out.println("获取某日期在月份中的天:" + localDate.getDayOfMonth());
        //获取某日期的在周中的天(字符串)
        System.out.println("获取某日期的在周中的天(字符串):" + localDate.getDayOfWeek());
        //获取某日期的在周中的天int
        System.out.println("获取某日期的在周中的天(int):" + localDate.get(ChronoField.DAY_OF_WEEK));
        //获取某日期的在年中的第?天
        System.out.println("获取某日期的在年中的第?天:" + localDate1.getDayOfYear());
        //获取某年的第一天
        LocalDate localDate2 = localDate.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("获取某年的第一天:" + localDate2);
        //获取某年的下一年的第一天
        LocalDate localDate3 = localDate.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("获取某年的下一年的第一天:" + localDate3);
        //获取某月的第一个周五
        LocalDate localDate4 = localDate.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY));
        System.out.println(localDate4);
        //获取某月的第一天
        LocalDate localDate5 = localDate.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("获取某月的第一天:" + localDate5);
        //获取某月的下个的第一天
        LocalDate localDate6 = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println("获取某月的下个的第一天:" + localDate6);

    }

运行结果:

获取当前日期:2021-01-21
自行构造日期:2020-12-09
获取某日期的年:2021
获取某日期的月(int):1
获取某日期的月(字符串):JANUARY
获取某日期在月份中的天:21
获取某日期的在周中的天(字符串):THURSDAY
获取某日期的在周中的天(int):4
获取某日期的在年中的第?天:344
获取某年的第一天:2021-01-01
获取某年的下一年的第一天:2022-01-01
2021-01-01
获取某月的第一天:2021-01-01
获取某月的下个的第一天:2021-02-01

2.LocalTime基本用法

 @Test
    public void testLocalTime() {
        //获取当前时分秒毫秒
        LocalTime localTime = LocalTime.now();
        System.out.println("获取当前时分秒毫秒:" + localTime);
        //自定义时分秒
        LocalTime localTime1 = LocalTime.of(12, 12, 11);
        System.out.println("自定义时分秒:" + localTime1);
        //自定义时分
        LocalTime localTime2 = LocalTime.of(12, 12);
        System.out.println("自定义时分:" + localTime2);
        //获取小时
        int hour = localTime.getHour();
        int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);
        System.out.println("获取小时:" + hour + ":::" + hour1);
        //获取分
        int minute = localTime.getMinute();
        int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);
        System.out.println("获取分:" + minute + ":::" + minute1);

        //获取秒
        int second = localTime.getSecond();
        int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println("获取秒:" + second + ":::" + second1);
    }

结果:

获取当前时分秒毫秒:10:20:46.178
自定义时分秒:12:12:11
自定义时分:12:12
获取小时:10:::10
获取分:20:::20
获取秒:46:::46

3.LocalDateTime基本用法

    @Test
    public void testLocalDateTime() {
        //获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("获取当前日期和时间:" + now);
        //自定义日期和时间
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.of(2022, 11, 3), LocalTime.now());
        System.out.println(localDateTime);
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime1 = localDate.atTime(localTime);
        System.out.println("localDateTime1:" + localDateTime1);
        LocalDateTime localDateTime2 = localTime.atDate(localDate);
        System.out.println("localDateTime2:" + localDateTime2);
        LocalDate localDate1 = now.toLocalDate();
        System.out.println("localDate1:" + localDate1);
        LocalTime localTime1 = now.toLocalTime();
        System.out.println("localTime1:" + localTime1);
        Instant instant = Instant.now();
        System.out.println("instant:" + instant);
        long epochSecond = instant.getEpochSecond();
        System.out.println("epochSecond:" + epochSecond);
        long epochMilli = instant.toEpochMilli();
        System.out.println("epochMilli:" + epochMilli + ":::" + System.currentTimeMillis());
        //当前日期时间加1年
        LocalDateTime localDateTime3 = now.plusYears(1);
        System.out.println("localDateTime3:" + localDateTime3);
        LocalDateTime localDateTime6 = now.plus(2, ChronoUnit.YEARS);
        System.out.println("localDateTime6:" + localDateTime3);
        //当前日期时间减1年
        LocalDateTime localDateTime4 = now.minusYears(1);
        System.out.println("localDateTime4:" + localDateTime4);
        LocalDateTime localDateTime5 = now.withYear(1999);
        System.out.println("localDateTime5:" + localDateTime5);
    }

结果:

BASIC_ISO_DATE:20210121
ISO_LOCAL_DATE:2021-01-21
ISO_DATE:2021-01-21
dateTimeFormatter1:2021/01/21
dateTimeFormatter2:2021/01/21 10:22:08
dateTimeFormatter3:2021-01-21 10:22:08
dateTimeFormatter4:2021.01.21 10:22:08
localDate1:1997-12-11
localDateTime1:1997-12-11T23:12:09
format8:1997-12-11 23:12:09
format9:2021年1月21日 上午10时22分08秒
format10:2021-1-21 10:22:08
format11:21-1-21 上午10:22

4.格式化

@Test
    public void testLocalDateFormat() {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate localDate = localDateTime.toLocalDate();
        LocalTime localTime = localDateTime.toLocalTime();
        String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("BASIC_ISO_DATE:" + format1);
        String format2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println("ISO_LOCAL_DATE:" + format2);
        String format3 = localDate.format(DateTimeFormatter.ISO_DATE);
        System.out.println("ISO_DATE:" + format3);
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String format4 = localDate.format(dateTimeFormatter1);
        System.out.println("dateTimeFormatter1:" + format4);
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String format5 = localDateTime.format(dateTimeFormatter2);
        System.out.println("dateTimeFormatter2:" + format5);
        DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format6 = localDateTime.format(dateTimeFormatter3);
        System.out.println("dateTimeFormatter3:" + format6);
        DateTimeFormatter dateTimeFormatter4 = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");
        String format7 = localDateTime.format(dateTimeFormatter4);
        System.out.println("dateTimeFormatter4:" + format7);
        LocalDate localDate1 = LocalDate.parse("1997-12-11", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println("localDate1:" + localDate1);

        //解析日期时间
        LocalDateTime localDateTime1 = LocalDateTime.parse("1997-12-11 23:12:09", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("localDateTime1:" + localDateTime1);
        String format8 = localDateTime1.format(dateTimeFormatter3);
        System.out.println("format8:" + format8);
        //日期本地化
        String format9 = localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG));
        System.out.println("format9:" + format9);
        //日期本地化
        String format10 = localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
        System.out.println("format10:" + format10);
        //日期本地化
        String format11 = localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT));
        System.out.println("format11:" + format11);
    }

结果:

BASIC_ISO_DATE:20210121
ISO_LOCAL_DATE:2021-01-21
ISO_DATE:2021-01-21
dateTimeFormatter1:2021/01/21
dateTimeFormatter2:2021/01/21 10:25:24
dateTimeFormatter3:2021-01-21 10:25:24
dateTimeFormatter4:2021.01.21 10:25:24
localDate1:1997-12-11
localDateTime1:1997-12-11T23:12:09
format8:1997-12-11 23:12:09
format9:2021年1月21日 上午10时25分24秒
format10:2021-1-21 10:25:24
format11:21-1-21 上午10:25

5.日期时间的简单计算

@Test
    public void testLocalDateCalc() {
        //带时区的日期与时间
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        System.out.println("带时区的日期与时间:" + zonedDateTime);
        //系统化默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("系统化默认时区:" + zoneId);
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = LocalDateTime.of(2021, 1, 21, 13, 45, 53);
        System.out.println("now:" + now);
        //两个日期时间的间隔
        //注意这里会向下取整 例如:间隔是1.8小时,那么间隔的day结果是1
        //其他同理
        Duration duration = Duration.between(now, localDateTime);
        System.out.println("两个日期的间隔秒:" + duration.getSeconds());
        System.out.println("两个日期的间隔天数:" + duration.toDays());
        System.out.println("两个日期的间隔小时:" + duration.toHours());
        //减去1年
        LocalDateTime localDateTime1 = now.minusYears(1);
        System.out.println("减去1年:" + localDateTime1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //减去1月
        LocalDateTime localDateTime2 = now.minusMonths(1);
        System.out.println("减去1月:" + localDateTime2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //减去1天
        LocalDateTime localDateTime3 = now.minusDays(1);
        LocalDateTime localDateTime4 = now.minus(Duration.ofDays(1));
        System.out.println("减去1天:" + localDateTime3.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println("减去1天localDateTime4:" + localDateTime4.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

结果:

带时区的日期与时间:2021-01-21T10:27:30.157+08:00[Asia/Shanghai]
系统化默认时区:Asia/Shanghai
now:2021-01-21T10:27:30.157
两个日期的间隔秒:11902
两个日期的间隔天数:0
两个日期的间隔小时:3
减去1年:2020-01-21 10:27:30
减去1月:2020-12-21 10:27:30
减去1天:2021-01-20 10:27:30
减去1天localDateTime4:2021-01-20 10:27:30

6.LocalDate转化为Date

    @Test
    public void localDateToDate() {
        LocalDate now = LocalDate.now();
        ZonedDateTime zonedDateTime = now.atStartOfDay(ZoneId.systemDefault());
        Date date = Date.from(zonedDateTime.toInstant());
        System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
    }

结果:

2021-01-21

7.Date转化为LocalDate

    @Test
    public void dateToLocalDate() {
        Date date = new Date();
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }

结果:

2021-01-21

8.LocalDateTime转化为Date

    @Test
    public void localDateTimeToDate() {
        LocalDateTime now = LocalDateTime.now();
        ZonedDateTime zdt = now.atZone(ZoneId.systemDefault());
        Date date = Date.from(zdt.toInstant());
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }

结果:

2021-01-21 10:32:22

9.Date转化为LocalDateTime

@Test
public void dateToLocalDateTime() {
    Date date = new Date();
    LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}

结果:

2021-01-21 10:34:17

10.LocalDateTime与数据库中datetime类型的使用

这里我使用springboot2.4.2+mybatis+mysql
数据库结构和数据如下:
在这里插入图片描述
在这里插入图片描述

CREATE TABLE `r_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='测试时间';

bean如下:

package com.example.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 测试时间表 r_test
 *
 * @author 
 * @date 2021-01-20
 */
public class Test {
    private static final long serialVersionUID = 1L;
    /**
     *
     */
    private Integer id;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("id", getId())
                .append("createTime", getCreateTime())
                .append("updateTime", getUpdateTime())
                .toString();
    }

}

使用controller访问:

package com.example.controller;

import com.example.domain.Test;
import com.example.service.ITestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 
 * @Description TODO
 * @Date 2021/1/20 18:37
 * @Version V1.0
 */
@RestController
@RequestMapping()
public class TestController {

    @Autowired
    private ITestService testService;

    @RequestMapping("test")
    public Test test() {
        Test test = testService.selectTestById(1);
        return test;
    }
}

访问结果:
在这里插入图片描述

11.示例代码

资源下载地址:
https://download.csdn.net/download/lvxinchun/14900851

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值