java8-LocalDate类

本文介绍Java 8中新的日期时间API,包括LocalDate、LocalTime、LocalDateTime等类的使用方法,并展示了如何利用DateTimeFormatter进行日期时间格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LocalDate类使用ISO日历表示年、月、日。

  • LocalDate.now(); 获取系统当前日期
  • LocalDate.of(int year,int month,int dayOfMonth);
    按指定日期创建LocalDate对象
  • getYear(); 返回日期中的年份
  • getMonth(); 返回月份
  • getDayOfMonth(); 返回月份中的日
1.LocalDate
package com.fantJ.JAVA_8;

import java.time.LocalDate;

public class LocalDate_Test {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        System.out.println(date.getYear()+" "+date.getMonthValue()+" "+date.getDayOfMonth());
        System.out.println(date.toString());
    }
}

img_ace97e7d07d6fb538516e0b11a9e76af.png
image.png
2.LocalTime
public class LocalTime_Test {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println(time.getHour()+" "+time.getMinute()+" "+time.getSecond());
        System.out.println(time.toString());
        System.out.println(time.toSecondOfDay());
    }
}
img_285124b138106dad3c03a1f386f9230e.png
image.png
3.LocalDateTime
public class LocalDateTime_Test {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(dateTime.getYear()+" "+dateTime.getMonthValue()+" "+dateTime.getDayOfMonth()+
                            dateTime.getHour()+" "+dateTime.getMinute()+" "+dateTime.getSecond());
        System.out.println(dateTime.toString());
    }
}
img_210e527f6f570d6c92a4f9bd1a57688c.png
image.png
4.DateTimeFormatter

用于将字符串解析为日期

public class DateTimeFormatter_Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse("2017-12-15:19:15:01",formatter);
        System.out.println(dateTime.toString());
    }
}
img_8580a29882bee68dd2eb728a9eddaea8.png
image.png
5.ZonedDateTime
public class ZonedDateTime_Test {
    public static void main(String[] args) {
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy:HH:mm:ss");
        String date = zonedDateTime.format(formatter);
        System.out.println(date);
    }
}
img_7d81c3d8adb8984ed2c43afb9c887304.png
image.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值