over 2 years ago

紀錄一下JDK8的時間與時域關係的取得方法,免得要用時找不到

不含時域時間取得方法

Instant timestamp = Instant.now();
System.out.println(timestamp);
//2015-07-20T02:00:15.638Z


Instant time = Calendar.getInstance().toInstant();
System.out.println(time);
//2015-07-20T02:00:15.638Z


Clock clock = Clock.systemDefaultZone();
System.out.println(clock.millis()); // 1395391162859

有關時域的取得方法

ZoneId defaultZone = TimeZone.getDefault().toZoneId();
System.out.println(defaultZone);
//Asia/Taipei


ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
System.out.println(gregorianCalendarDateTime);
//2015-07-20T10:05:18.825+08:00[Asia/Taipei]


ZoneOffset zoneOffset = ZoneOffset.ofHours(1);  
System.out.println(zoneOffset.toString()); // +01:00  

  
ZoneId zone1 = ZoneId.of("Asia/Tokyo");  
System.out.println(zone1.getRules()); // ZoneRules[currentStandardOffset=+09:00]  

LocalTime now1 = LocalTime.now(zone1);  
System.out.println(now1); // 17:39:22.890  

  
ZonedDateTime jaTime = ZonedDateTime.of(2014, 1, 31, 10, 0, 0, 0, zone1);  
System.out.println(jaTime); // 2014-01-31T10:00+09:00[Asia/Tokyo]  

日期轉換

LocalDate changeDate1 = LocalDate.of(2013, 12, 4);
System.out.println(changeDate1);
// 2013-12-04

LocalDateTime changeDateTime1 = changeDate1.atTime(10, 30, 45);
System.out.println(changeDateTime1);
// 2013-12-04T10:30:45

LocalDate formatDate2 = LocalDate.parse("2013/12/04", DateTimeFormatter.ofPattern("yyyy/MM/dd"));  
System.out.println(formatDate2);
// 2013-12-04

日期格式化

LocalDateTime dateTime = LocalDateTime.now();
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-M-d")));
// 2015-7-20

System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
// 20::七月::2015 10::08::36

System.out.println(dateTime.format(DateTimeFormatter.ISO_DATE_TIME));
// 2015-07-20T10:08:36.888

日期加減

LocalDate today = LocalDate.now();
LocalDate twoDaysAfter = today.plusDays(2L); // 2天后

LocalDate threeDaysBefore = today.minusDays(3L); // 3天前

LocalDate oneYearsAfter = today.plus(1L, ChronoUnit.YEARS);// 1年後

LocalDate twoWeeksBefore = today.minus(2L, ChronoUnit.WEEKS); // 2周前

LocalDate newDate = LocalDate.now().plus(Period.of(3, 2, 1)); // 3年2月1天后

跟java.util.Date轉換

// LocalDateTime -> Date

LocalDateTime cDateTime = LocalDateTime.now();
Instant instant = cDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date cDate = Date.from(instant);
System.out.println(cDate); // Fri Mar 21 16:39:22 CST 2014

 
// Date -> LocalDateTime

Date date2 = new Date();
Instant instant2 = date2.toInstant();
LocalDateTime dateTimeFromDate = LocalDateTime.ofInstant(instant2, ZoneOffset.systemDefault());
System.out.println(dateTimeFromDate); // 2014-03-21T16:39:22.890


// Calendar -> LocalDateTime

Calendar cal = Calendar.getInstance();
LocalDateTime dateTimeFromCal = LocalDateTime.ofInstant(cal.toInstant(), ZoneOffset.systemDefault());
System.out.println(dateTimeFromCal); // 2014-03-21T16:39:22.890

日本時間

JapaneseDate jdate1 = JapaneseDate.of(2013, 12, 4);
System.out.println(jdate1); // Japanese Heisei 25-12-04    

JapaneseDate jdate2 = JapaneseDate.of(JapaneseEra.HEISEI, 25, 12, 4);
System.out.println(jdate2); // Japanese Heisei 25-12-04

不同月曆系統轉換

LocalDate birth = LocalDate.of(1982, 3, 18);
MinguoDate mingoBirth = MinguoDate.from(birth);
System.out.println(mingoBirth);  // Minguo ROC 71-03-18

System.out.println(LocalDate.from(mingoBirth));//1982-03-18

或是

/*
 * Convert LocalDate -> ChronoLocalDate -> String and back.
 */

public class Main {

  /**
   * Converts a LocalDate (ISO) value to a ChronoLocalDate date using the
   * provided Chronology, and then formats the ChronoLocalDate to a String using
   * a DateTimeFormatter with a SHORT pattern based on the Chronology and the
   * current Locale.
   *
   * @param localDate
   *          - the ISO date to convert and format.
   * @param chrono
   *          - an optional Chronology. If null, then IsoChronology is used.
   */
  public static String toString(LocalDate localDate, Chronology chrono) {
    if (localDate != null) {
      Locale locale = Locale.getDefault(Locale.Category.FORMAT);
      ChronoLocalDate cDate;
      if (chrono == null) {
        chrono = IsoChronology.INSTANCE;
      }
      try {
        cDate = chrono.date(localDate);
      } catch (DateTimeException ex) {
        System.err.println(ex);
        chrono = IsoChronology.INSTANCE;
        cDate = localDate;
      }
      String pattern = "M/d/yyyy GGGGG";
      DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
      return dateFormatter.format(cDate);
    } else {
      return "";
    }
  }

  /**
   * Parses a String to a ChronoLocalDate using a DateTimeFormatter with a short
   * pattern based on the current Locale and the provided Chronology, then
   * converts this to a LocalDate (ISO) value.
   *
   * @param text
   *          - the input date text in the SHORT format expected for the
   *          Chronology and the current Locale.
   *
   * @param chrono
   *          - an optional Chronology. If null, then IsoChronology is used.
   */
  public static LocalDate fromString(String text, Chronology chrono) {
    if (text != null && !text.isEmpty()) {
      Locale locale = Locale.getDefault(Locale.Category.FORMAT);
      if (chrono == null) {
        chrono = IsoChronology.INSTANCE;
      }
      String pattern = "M/d/yyyy GGGGG";
      DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
          .appendPattern(pattern).toFormatter().withChronology(chrono)
          .withDecimalStyle(DecimalStyle.of(locale));
      TemporalAccessor temporal = df.parse(text);
      ChronoLocalDate cDate = chrono.date(temporal);
      return LocalDate.from(cDate);
    }
    return null;
  }

  public static void main(String[] args) {
    LocalDate date = LocalDate.of(1996, Month.OCTOBER, 29);
    System.out.printf("%s%n", toString(date, JapaneseChronology.INSTANCE));
    System.out.printf("%s%n", toString(date, MinguoChronology.INSTANCE));
    System.out.printf("%s%n", toString(date, ThaiBuddhistChronology.INSTANCE));
    System.out.printf("%s%n", toString(date, HijrahChronology.INSTANCE));

    System.out.printf("%s%n",
        fromString("10/29/0008 H", JapaneseChronology.INSTANCE));
    System.out.printf("%s%n",
        fromString("10/29/0085 1", MinguoChronology.INSTANCE));
    System.out.printf("%s%n",
        fromString("10/29/2539 B.E.", ThaiBuddhistChronology.INSTANCE));
    System.out.printf("%s%n",
        fromString("6/16/1417 1", HijrahChronology.INSTANCE));
  }
}

上面的方法客製化民國轉西元

Locale locale = Locale.getDefault(Locale.Category.FORMAT);
Chronology chrono = MinguoChronology.INSTANCE;
DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
        .appendPattern("(yy/MM/dd HH:mm:ss)").toFormatter().withChronology(chrono)
        .withDecimalStyle(DecimalStyle.of(locale));
TemporalAccessor temporal = df.parse("(92/06/23 16:20:43)");
ChronoLocalDate cDate = chrono.date(temporal);
System.out.println(LocalDate.from(cDate));
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(ZoneId.systemDefault()); // UTC

// ZonedDateTime

System.out.println(Instant.now().atZone(ZoneId.of("UTC"))); // 2017-05-04T06:11:43.395Z[UTC]

System.out.println(Instant.now().atZone(ZoneId.of("Asia/Shanghai"))); // 2017-05-04T14:11:43.400+08:00[Asia/Shanghai]

// OffsetDateTime

System.out.println(Instant.now().atOffset(ZoneOffset.UTC)); // 2017-05-04T06:11:43.467Z

System.out.println(Instant.now().atOffset(ZoneOffset.of("+8"))); // 2017-05-04T14:11:43.467+08:00


Instant instant = Instant.now();
instant.plus(3, ChronoUnit.DAYS);


// 五天後上海時間 23:59:59

ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
zonedDateTime = zonedDateTime.plusDays(5);
zonedDateTime = zonedDateTime.withHour(23);
zonedDateTime = zonedDateTime.withMinute(59);
zonedDateTime = zonedDateTime.withSecond(59);
System.out.println(zonedDateTime); // 2017-05-09T23:59:59.467+08:00[Asia/Shanghai]

Instant instant = zonedDateTime.toInstant();
System.out.println(instant); // 2017-05-09T15:59:59.467Z

Date date = Date.from(instant);
System.out.println(date); // Tue May 09 15:59:59 UTC 2017


String input = "2017-05-04";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(input, formatter);
// ZonedDateTime

System.out.println(localDate.atStartOfDay(ZoneId.of("UTC"))); // 2017-05-04T00:00Z[UTC]

System.out.println(localDate.format(formatter)); // 2017-05-04

參考
Java8 日期/时间(Date Time)API指南
Convert date to different Date system
Java8で追加された型・メソッド一覧

← Spring BCryptPasswordEncoder 使用Spring-Boot整合Spring-Data操作ElasticSearch →
 
comments powered by Disqus