JAVA格式化⽇期、时间的⽅法
使⽤ DateFormat 格式化⽇期、时间
DateFormat 也是⼀个抽象类,它也提供了如下⼏个类⽅法⽤于获取 DateFormat 对象。
getDateInstance():返回⼀个⽇期格式器,它格式化后的字符串只有⽇期,没有时间。该⽅法可以传⼊多个参数,⽤于指定⽇期样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
getTimeInstance():返回⼀个时间格式器,它格式化后的字符串只有时间,没有⽇期。该⽅法可以传⼊多个参数,⽤于指定时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
getDateTimeInstance():返回⼀个⽇期、时间格式器,它格式化后的字符串既有⽇期,也有时间。该⽅法可以传⼊多个参数,⽤于指定⽇期样式、时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
上⾯三个⽅法可以指定⽇期样式、时间样式参数,它们是的4个静态常量:FULL、LONG、MEDIUM 和 SHORT,通过这4个样式参数可以控制⽣成的格式化字符串。看如下例⼦程序。
import java.util.*;
*;
import DateFormat.*;
public class DateFormatTest {
public static void main(String[] args) throws ParseException {
// 需要被格式化的时间
Date dt = new Date();
// 创建两个Locale,分别代表中国、美国
Locale[] locales = { Locale.CHINA, Locale.US };
DateFormat[] df = new DateFormat[16];
// 为上⾯两个Locale创建16个DateFormat对象
for (int i = 0; i < locales.length; i++) {
df[i * 8] = DateInstance(SHORT, locales[i]);
df[i * 8 + 1] = DateInstance(MEDIUM, locales[i]);
df[i * 8 + 2] = DateInstance(LONG, locales[i]);
df[i * 8 + 3] = DateInstance(FULL, locales[i]);
df[i * 8 + 4] = TimeInstance(SHORT, locales[i]);
df[i * 8 + 5] = TimeInstance(MEDIUM, locales[i]);
df[i * 8 + 6] = TimeInstance(LONG, locales[i]);
df[i * 8 + 7] = TimeInstance(FULL, locales[i]);
}
for (int i = 0; i < locales.length; i++) {
String tip = i == 0 ? "----中国⽇期格式----" : "----美国⽇期格式----";
System.out.println(tip);
System.out.println("SHORT格式的⽇期格式:" + df[i * 8].format(dt));
System.out.println("MEDIUM格式的⽇期格式:" + df[i * 8 + 1].format(dt));
System.out.println("LONG格式的⽇期格式:" + df[i * 8 + 2].format(dt));
System.out.println("FULL格式的⽇期格式:" + df[i * 8 + 3].format(dt));
System.out.println("SHORT格式的时间格式:" + df[i * 8 + 4].format(dt));
System.out.println("MEDIUM格式的时间格式:" + df[i * 8 + 5].format(dt));
System.out.println("LONG格式的时间格式:" + df[i * 8 + 6].format(dt));
System.out.println("FULL格式的时间格式:" + df[i * 8 + 7].format(dt));
}
}
}
上⾯程序共创建了16个 DateFormat 对象,分别为中国、美国两个 Locale 各创建8个 DateFormat 对象,分别是 SHORT、MEDIUM、LONG、FULL 四种样式的⽇期格式器、时间格式器。运⾏上⾯程序,会看到如下所⽰的效果。
----中国⽇期格式----
SHORT格式的⽇期格式:20-2-11
MEDIUM格式的⽇期格式:2020-2-11
LONG格式的⽇期格式:2020年2⽉11⽇
FULL格式的⽇期格式:2020年2⽉11⽇星期⼆
SHORT格式的时间格式:下午2:26
MEDIUM格式的时间格式:14:26:21
LONG格式的时间格式:下午02时26分21秒
FULL格式的时间格式:下午02时26分21秒 CST
----美国⽇期格式----
SHORT格式的⽇期格式:2/11/20
MEDIUM格式的⽇期格式:Feb 11, 2020
LONG格式的⽇期格式:February 11, 2020
FULL格式的⽇期格式:Tuesday, February 11, 2020
SHORT格式的时间格式:2:26 PM
MEDIUM格式的时间格式:2:26:21 PM
LONG格式的时间格式:2:26:21 PM CST
FULL格式的时间格式:2:26:21 PM CST
DateFormat 具有国际化的能⼒,同⼀个⽇期使⽤不同的 Locale 格式器格式化的效果完全不同,格式化后的字符串正好符合Locale 对应的本地习惯。
获得了 DateFormat 之后,还可以调⽤它的 setLenient(boolean lenient) ⽅法来设置该格式器是否采⽤严格语法。举例来说,如果采⽤不严格的⽇期语法(该⽅法的参数为true),对于字符串"2004-2-31"将会转换成2004年3⽉2⽇:如果采⽤严格的⽇期语法,解析该字符串时将抛出异常。
DateFormat 的 parse() ⽅法可以把⼀个字符串解析成 Date 对象,但它要求被解析的字符串必须符合⽇期字符串的要求,否则可能抛出 ParseExcepuon 异常。例如,如下代码⽚段:
String str1 = "2017/10/07";
String str2 = "2017年10⽉07⽇";
// 下⾯输出 Sat Oct 07 00:00:00 CST 2017
System.out.DateInstance().parse(str2));
// 下⾯输出 Sat Oct 07 00:00:00 CST 2017
System.out.DateInstance(SHORT).parse(str1));
// 下⾯抛出 ParseException异常
System.out.DateInstance().parse(str1));
上⾯代码中最后⼀⾏代码解析⽇期字符串时引发 ParseException 异常,因为"2017/10/07"是⼀个 SHORT 样式的⽇期字符串,必须⽤ SHORT 样式的 DateFormat 实例解析,否则将抛出异常。
使⽤ SimpleDateFormat 格式化⽇期
前⾯介绍的 DateFormat 的⽅法可以把字符串解析成 Date 对象,但实际上 DateFormat 的 parse() ⽅法不够灵活⼀⼀它要求被解析的字符串必须满⾜特定的格式!为了更好地格式化⽇期、解析⽇期字符串,Java 提供了 SimpleDateFormat 类。
SimpleDateFormat 是 DateFormat 的⼦类,正如它的名字所暗⽰的,它是“简单”的⽇期格式器。很多读者对“简单”的⽇期格式器不屑⼀顾,实际上 SimpleDateFormat ⽐ DateFormat 更简单,功能更强⼤。
SimpleDateFormat 可以⾮常灵活地格式化 Date,也可以⽤于解析各种格式的⽇期字符串。创建 SimpleDateFormat 对象时需要传⼊⼀个 pattern 字符串,这个 pattern 不是正则表达式,⽽是⼀个⽇期模板字符串。
*;
import java.util.*;
public class SimpleDateFormatTest {
public static void main(String[] args) throws ParseException {
Date d = new Date();
// 创建⼀个SimpleDateFormat对象
SimpleDateFormat sdf1 = new SimpleDateFormat("Gyyyy年中第D天");
// 将d格式化成⽇期,输出:公元2017年中第282天
String dateStr = sdf1.format(d);
System.out.println(dateStr);
// ⼀个⾮常特殊的⽇期字符串
String str = "14###3⽉##21";
SimpleDateFormat sdf2 = new SimpleDateFormat("y###MMM##d");
// 将⽇期字符串解析成⽇期,输出:Fri Mar 21 00:00:00 CST 2014
System.out.println(sdf2.parse(str));
}
}
从上⾯程序中可以看出,使⽤ SimpleDateFormat 可以将⽇期格式化成形如“公元2014年中第101天”这样的字符串,也可以把形如“14###3⽉##21”这样的字符串解析成⽇期,功能⾮常强⼤。
SimpleDateFormat 把⽇期格式化成怎样的字符串,以及能把怎样的字符串解析成 Date,完全取决于创建该对象时指定的pattern 参数,pattern 是⼀个使⽤⽇期字段占位符的⽇期模板。
如果读者想知道 SimpleDateFormat ⽀持哪些⽇期、时间占位符,可以查阅 API ⽂档中 SimpleDateFormat 类的说明,此处不再赘述。
Java 8 新增的⽇期、时间格式器
Java 8 新增的⽇期、时间 API ⾥不仅包括了 Instant、LocalDate、LocalDateTime、LocalTime 等代表⽇期、时间的类,⽽且
在 java.time.format 包下提供了⼀个 DateTimeFormatter 格式器类,该类相当于前⾯介绍的 DateFormat 和 SimpleDateFormat 的合体,功能⾮常强⼤。
与 DateFormat、SimpleDateFormat 类似,DateTimeFormatter 不仅可以将⽇期、时间对象格式化成字符串,也可以将特定格式的字符串解析成⽇期、时间对象。
为了使⽤ DateTimeFormatter 进⾏格式化或解析,必须先获取 DateTimeFormatter 对象,获取 DateTimeFormatter 对象有如下三种常见的⽅式。
直接使⽤静态常量创建 DateTimeFormatter 格式器。DateTimeFormatter 类中包含了⼤量形如 ISO_LOCAL_DATE、ISO_LOCAL_TIME、ISO_LOCAL_DATE_TIME 等静态常量,这些静态常量本⾝就是 DateTimeFormatter 实例。
使⽤代表不同风格的枚举值来创建 DateTimeFormatter 格式器。在 FormatStyle 枚举类中定义了 FULL、LONG、MEDIUM、SHORT 四个枚举值,它们代表⽇期、时间的不同风格。
根据模式字符串来创建 DateTmeFormatter 格式器。类似于 SimpleDateFormat,可以采⽤模式字符串
来创建
DateTimeFormatter,如果需要了解⽀持哪些模式字符串,则需要参该类的 API ⽂档。
使⽤ DateTimeFormatter 完成格式化
使⽤ DateTimeFormatter 将⽇期、时间(LocalDate、LocalDateTime、LocalTime等实例)格式化为字符串,可通过如下两种⽅式。
调⽤ DateTimeFormatter 的 format(TemporalAccessor temporal) ⽅法执⾏格式化,其中 LocalDate、LocalDateTime、LocalTime 等类都是 TemporalAccessor 接⼝的实现类。
调⽤ LocalDate、LocalDateTime、LocalTime 等⽇期、时间对象的 format(DateTimeFormatter formatter) ⽅法执⾏格式化。
上⾯两种⽅式的功能相同,⽤法也基本相似,如下程序⽰范了使⽤ DateTimeFormatter 来格式化⽇期、时间。
import java.time.*;
import java.time.format.*;
public class NewFormatterTest{
public static void main(String[] args){
DateTimeFormatter[] formatters = new DateTimeFormatter[]{
// 直接使⽤常量创建DateTimeFormatter格式器
DateTimeFormatter.ISO_LOCAL_DATE,
DateTimeFormatter.ISO_LOCAL_TIME,
DateTimeFormatter.ISO_LOCAL_DATE_TIME,
// 使⽤本地化的不同风格来创建DateTimeFormatter格式器
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG),
// 根据模式字符串来创建DateTimeFormatter格式器
DateTimeFormatter.ofPattern("Gyyyy%%MMM%%dd HH:mm:ss")
};
LocalDateTime date = w();
// 依次使⽤不同的格式器对LocalDateTime进⾏格式化
for(int i = 0 ; i < formatters.length ; i++){
// 下⾯两⾏代码的作⽤相同
System.out.println(date.format(formatters[i]));
System.out.println(formatters[i].format(date));
}
}
}
上⾯程序使⽤三种⽅式创建了6个 DateTimeFormatter 对象,然后程序中两⾏粗体字代码分别使⽤不同⽅式来格式化⽇期。运⾏上⾯程序,会看到如下所⽰的效果。
2020-02-11
2020-02-11
17:13:00.303
17:13:00.303
2020-02-11T17:13:00.303
2020-02-11T17:13:00.303
2020年2⽉11⽇星期⼆ 17:13:00
2020年2⽉11⽇星期⼆ 17:13:00
2020年2⽉11⽇
2020年2⽉11⽇
公元2020%%⼆⽉%%11 17:13:00
公元2020%%⼆⽉%%11 17:13:00
可以看出,使⽤ DateTimeFormatter 进⾏格式化,也可使⽤模式字符串对⽇期、时间进⾏⾃定义格式化,由此可见,功能完全覆盖了传统的 DateFormat、SimpleDateFormate 的功能。
提⽰:有些时候,读者可能还需要使⽤传统的 DateFormat 来执⾏格式化,DateTimeFormatter 则提供了⼀个 toFormat() ⽅法,该⽅法可以获取 DateTimeFormatter 对应的 Format 对象。
使⽤ DateTimeFormatter 解析字符串
为了使⽤ DateTimeFormatter 将指定格式的字符串解析成⽇期、时间对象(LocalDate、LocalDateTime、LocalTime 等实例),可通过⽇期、时间对象提供的 parse(CharSequence text,DateTimeFormatter formatter) ⽅法进⾏解析。
如下程序⽰范了使⽤ DateTimeFormatter 解析⽇期、时间字符串。
import java.time.*;
import java.time.format.*;
public class NewFormatterParse {
public static void main(String[] args) {时间正则表达式java
// 定义⼀个任意格式的⽇期时间字符串
String str1 = "2014==04==12 01时06分09秒";
// 根据需要解析的⽇期、时间字符串定义解析所⽤的格式器
DateTimeFormatter fomatter1 = DateTimeFormatter.ofPattern("yyyy==MM==dd HH时mm分ss秒");
// 执⾏解析
LocalDateTime dt1 = LocalDateTime.parse(str1, fomatter1);
System.out.println(dt1); // 输出 2014-04-12T01:06:09
// ---下⾯代码再次解析另⼀个字符串---
String str2 = "2014$$$4⽉$$$13 20⼩时";
DateTimeFormatter fomatter2 = DateTimeFormatter.ofPattern("yyy$$$MMM$$$dd HH⼩时");
LocalDateTime dt2 = LocalDateTime.parse(str2, fomatter2);
System.out.println(dt2); // 输出 2014-04-13T20:00
}
}
上⾯程序中定义了两个不同格式的⽇期、时间字符串,为了解析它们,程序分别使⽤对应的格式字符串创建了DateTmeFormatter 对象,这样 DateTimeFormatter 即可按该格式字符串将⽇期、时间字符串解析成 LocalDateTime 对象。编译、运⾏该程序,即可看到两个⽇期、时间字符串都被成功地解析成 LocalDateTime。
以上就是JAVA 格式化⽇期、时间的⽅法的详细内容,更多关于JAVA 格式化⽇期、时间的资料请关注其它相关⽂章!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。