Java 8日期解析和格式化实例

x33g5p2x  于2021-08-22 转载在 Java  
字(4.8k)|赞(0)|评价(0)|浏览(382)

1. 概述

Date-Time API中的基于时间的类提供了解析方法,用于解析包含日期和时间信息的字符串。这些类还提供了格式化方法,用于格式化基于时间的对象以进行显示。在这两种情况下,过程是相似的:你向DateTimeFormatter提供一个模式,以创建一个formatter对象。然后这个格式化器被传递给解析或格式化方法。

  • 如果在转换过程中出现问题,parseformat方法会抛出一个异常。因此,你的解析代码应该捕获DateTimeParseException错误,你的格式代码应该捕获DateTimeException错误。关于异常处理的更多信息,请参见捕获和处理异常。
    DateTimeFormatter类提供了许多预定义的格式器,或者你可以定义你自己的。
    让我们在我们的例子中使用一些预定义的格式化。本指南的例子可以在Github上找到。

2. 解析

LocalDate类中的单参数parse(CharSequence)方法使用ISO_LOCAL_DATE格式化。要指定一个不同的格式,你可以使用双参数parse(CharSequence, DateTimeFormatter)方法。
下面的例子使用了预定义的BASIC_ISO_DATE格式,它使用1959年7月9日的格式19590709。

String in = ...;
LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);

2.1 LocalDate类格式化和Parsing示例

package com.ramesh.java8.datetime;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

public class LocalDateFormat {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
private static final DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("d-MMM-yyyy");
private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("d/MM/yyyy");
public static void main(String[] args) {
 //default format
 System.out.println("Default format of LocalDate = " + LocalDate.now());
   
 // The ISO date formatter that formats or parses a date without an
  // offset, such as '20111203'
 LocalDate date = LocalDate.now();
 
 System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));
 
 System.out.println(date.format(DateTimeFormatter.ISO_DATE));
 
 System.out.println(formatter.format(LocalDate.parse("16/08/2016", formatter)));
 
 System.out.println(formatter1.format(LocalDate.parse("16-Aug-2016", formatter1)));
 
 System.out.println(formatter2.format(LocalDate.parse("16/08/2016", formatter2)));
}
}

输出。

Default format of LocalDate = 2018-07-11
20180711
2018-07-11
16/08/2016
16-Aug-2016
16/08/2016

3. 格式化

format(DateTimeFormatter)方法使用指定的格式将一个基于时间的对象转换为字符串表示。

3.1 ZonedDateTime类格式化与飞行实例

下面的Flight例子,使用 "MMM d yyy hh:mm a "的格式转换了ZonedDateTime的一个实例。日期的定义方式与前一个解析例子的方式相同,但这个模式还包括小时、分钟、上午和下午的成分。

package com.ramesh.java8.datetime;

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
//*
/* This example uses ZonedDateTime to calculate the arrival time of
/* a flight that leaves from San Francisco and arrives in Tokyo.
/* The flight is 10 hours, 50 minutes long. Formatters are used to
/* print the departure and arrival times.
/*/

public class FlightZoneDateTimeExample {
    public static void main(String[] args) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");

        // Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
        LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
        ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); 
        ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);

        try {
            String out1 = departure.format(format);
            System.out.printf("LEAVING:  %s (%s)%n", out1, leavingZone);
        } catch (DateTimeException exc) {
            System.out.printf("%s can't be formatted!%n", departure);
            throw exc;
        }

        // Flight is 10 hours and 50 minutes, or 650 minutes
        ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); 
        ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone)
                                         .plusMinutes(650);

        try {
            String out2 = arrival.format(format);
            System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
        } catch (DateTimeException exc) {
            System.out.printf("%s can't be formatted!%n", arrival);
            throw exc;
        }

        if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) 
            System.out.printf("  (%s daylight saving time will be in effect.)%n",
                              arrivingZone);
        else
            System.out.printf("  (%s standard time will be in effect.)%n",
                              arrivingZone);
    }
}

输出。

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)
  (Asia/Tokyo standard time will be in effect.)

3.2 LocalDateTime类格式化和解析示例

package com.ramesh.java8.datetime;

import java.time.Instant;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeFormat {
 
public static void main(String[] args) {
  
  LocalDateTime dateTime = LocalDateTime.now();
  
  //default format
  System.out.println("Default format of LocalDateTime="+dateTime);
  
  //specific format
  System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
  
  System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
  
  Instant timestamp = Instant.now();
  
  //default format
  System.out.println("Default format of Instant="+timestamp);
  
  //Parse examples
  LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
    DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
  System.out.println("Default format after parsing = "+dt);
 }
}

输出。

Default format of LocalDateTime=2018-07-11T16:24:57.130
11::Jul::2018 16::24::57
20180711
Default format of Instant=2018-07-11T10:54:57.179Z
Default format after parsing = 2014-04-27T21:39:48

相关文章