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

Java 函数库中的常用日期格式化工具
java.time 是 Java 8 中引入的一个日期和时间 API,为日期和时间处理提供了丰富的功能,其中包括多个常用的日期格式化工具。
SimpleDateFormat:
立即学习“Java免费学习笔记(深入)”;
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);
}
}以上就是Java 函数库中都有哪些常用日期格式化工具?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号