LoginSignup
1

More than 5 years have passed since last update.

Java8のJava.time APIを用いてユーティリティを書いてみた。

Last updated at Posted at 2016-06-23

Java8のJava.time APIを用いてユーティリティを書いてみた。

Java8のnew DateTimeFormatter.ofPattern("yyyy/MM/dd")は、1980/1/1がParseエラーとなる。
1980/01/01ならOK。

これなら旧来のnew SimpleDateFormat("yyyy/MM/dd")の方が使い勝手が良い気がする。
もうちょっと研究が必要かな。

MyDateUtil.java
package com.example.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

public class MyDateUtil {

    /**
     * Parse String to Date.
     * (Using Java8 java.time....)
     * 
     * @param birthDay "yyyy/MM/dd" format
     * @return java.util.Date
     */
    public static Date parse(String date) {

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        TemporalAccessor ta = fmt.parse(date);
            ZonedDateTime zdt = LocalDate.from(ta).atTime(0, 0).atZone(ZoneId.of("Asia/Tokyo"));
            return  Date.from(zdt.toInstant());
    }

    /**
     * Using traditional Java.util.Date
     *  @param Object "yyyy/MM/dd" format String
     *  return java.util.Date
     */
    public static Date toDate(Object object) {
        String in = object.toString();
        Date date;
        DateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
        try {
            date = formater.parse(in);
            return date;
        } catch (ParseException e) {
            return null;
        }
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1