登录
首页 >  文章 >  java教程

Java 函数库中都有哪些常用日期格式化工具?

时间:2024-05-01 09:41:37 233浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Java 函数库中都有哪些常用日期格式化工具?》,这篇文章主要讲到等等知识,如果你对文章相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

Java 函数库提供了多种日期格式化工具:SimpleDateFormat:可使用模式字符串格式化和解析日期。(例如:yyyy-MM-dd)DateTimeFormatter:java.time API 中提供的更全面的格式化工具,通过模式字符串创建。(例如:yyyy-MM-dd)Joda-Time:Apache 社区的日期和时间库,提供更高级的功能。(例如:时区处理,日期范围操作)

Java 函数库中都有哪些常用日期格式化工具?

Java 函数库中的常用日期格式化工具

java.time 是 Java 8 中引入的一个日期和时间 API,为日期和时间处理提供了丰富的功能,其中包括多个常用的日期格式化工具。

SimpleDateFormat:

SimpleDateFormat 类提供了一种对日期和时间进行格式化和解析的方式。它使用一个模式字符串来定义所需的格式,如 yyyy-MM-dd

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

    public static void main(String[] args) {
        Date date = new Date();
        
        // 使用模式字符串进行格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(date);
        System.out.println("格式化后的日期:" + formattedDate);
        
        // 使用解析字符串进行解析
        SimpleDateFormat sdfParse = new SimpleDateFormat("yyyy-MM-dd");
        Date parsedDate = sdfParse.parse(formattedDate);
        System.out.println("解析后的日期:" + parsedDate);
    }
}

DateTimeFormatter:

DateTimeFormatter 类是 java.time API 中引入的,它提供了更全面和可配置的日期格式化功能。通过 ofPattern 方法指定模式字符串来创建 DateTimeFormatter 实例。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {

    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        
        // 使用模式字符串创建 DateTimeFormatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        // 格式化日期
        String formattedDate = dtf.format(date);
        System.out.println("格式化后的日期:" + formattedDate);
        
        // 解析日期
        LocalDate parsedDate = LocalDate.parse(formattedDate, dtf);
        System.out.println("解析后的日期:" + parsedDate);
    }
}

Joda-Time:

Joda-Time 是 Apache 社区开发的一个广泛使用的日期和时间 API。它提供了 java.time API 没有的额外功能,例如时区处理和日期范围操作。

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class JodaTimeExample {

    public static void main(String[] args) {
        DateTime dateTime = new DateTime();
        
        // 使用模式字符串创建 DateTimeFormatter
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        
        // 格式化日期
        String formattedDate = dtf.print(dateTime);
        System.out.println("格式化后的日期:" + formattedDate);
        
        // 解析日期
        DateTime parsedDateTime = dtf.parseDateTime(formattedDate);
        System.out.println("解析后的日期:" + parsedDateTime);
    }
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>