【Java】 日付・時間 について ~ 基本編 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2014/11/18/235600

の続き。

 ■ 現在時刻を取得する

[1] Date を使用する場合

import java.util.Date;

Date date = new Date();
// Tue Nov 18 23:53:23 JST 2014
System.out.println(date.toString());

[2] Calendar を使用する場合

import java.util.Calendar;

Calendar current = Calendar.getInstance();
// Tue Nov 18 23:48:05 JST 2014
System.out.println(current.getTime());

[3] (ミリ秒単位であれば)System.currentTimeMillis()を使用する場合

* 詳細は、以下の関連記事を参照のこと。

https://dk521123.hatenablog.com/entry/2017/04/25/223122
 サンプル

long now = System.currentTimeMillis();
// 1416322490702
System.out.println(now);

 ■ 日付のフォーマットを指定する

 * SimpleDateFormat を利用する

 サンプル

import java.text.SimpleDateFormat;
import java.util.Date;

SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
// 2014/11/19 00:04:40.428
System.out.println(dateFormatter.format(new Date()));

 ■ 年月日時間を個別で取る

各要素については、以下のサイトを参照のこと。 

http://java-code.jp/221

Calendar calendar = Calendar.getInstance();
int year   = calendar.get(Calendar.YEAR);
int month  = calendar.get(Calendar.MONTH);
int day    = calendar.get(Calendar.DAY_OF_MONTH);
int hour   = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

個別設定

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2006);

https://www.javadrive.jp/start/calendar/index3.html

 ■ 日時のリストに対して、対象の日時に近いデータでソートする

 サンプル

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {

  public static void main(String[] args) throws Exception {
    List<Calendar> inputValues = new ArrayList<>();
    inputValues.add(getCalendar(2016, 9, 12, 20, 11, 0));
    inputValues.add(getCalendar(2016, 1, 21, 19, 22, 0));
    inputValues.add(getCalendar(2016, 9, 12, 23, 22, 0));
    inputValues.add(getCalendar(2017, 11, 21, 19, 22, 0));
    inputValues.add(getCalendar(2016, 9, 21, 21, 11, 0));
    inputValues.add(getCalendar(2017, 1, 21, 19, 22, 0));
    inputValues.add(getCalendar(2015, 1, 21, 19, 22, 0));
    inputValues.add(getCalendar(2016, 11, 21, 19, 22, 0));
    inputValues.add(getCalendar(2015, 1, 21, 19, 22, 0));
    inputValues.add(getCalendar(2016, 10, 12, 23, 11, 0));
    inputValues.add(getCalendar(2016, 1, 21, 19, 22, 0));
    inputValues.add(getCalendar(2017, 1, 21, 19, 22, 0));

    Calendar current = Calendar.getInstance();

    String inputData = toString(current, "yyyy-MM-dd HH:mm:ss");
    System.out.println("Input Data : " + inputData);
    
    Calendar nearestDatetime = findNearestDatetime(inputValues, current);
    String resultNearestDatetime = toString(nearestDatetime, "yyyy-MM-dd HH:mm:ss");
    System.out.println("Nearest Datetime : " + resultNearestDatetime);
    
    sortByNearestDatetime(inputValues, current);
    int index = 1;
    for (Calendar value : inputValues) {
      String result = toString(value, "yyyy-MM-dd HH:mm:ss");
      System.out.println("Result [" + index + "] : " + result);
      index++;
    }
  }

  private static Calendar getCalendar(int year, int month, int date, int hourOfDay, int minute, int second) {
    Calendar returnValue = Calendar.getInstance();
    returnValue.set(year, month, date, hourOfDay, minute, second);
    return returnValue;
  }

  private static String toString(Calendar targetValue, String dateFormat) throws Exception {
    SimpleDateFormat dateformat = new SimpleDateFormat(dateFormat);
    try {
      return dateformat.format(targetValue.getTime());
    } catch (Exception ex) {
      throw ex;
    }
  }

  // ★ここ★
  private static Calendar findNearestDatetime(List<Calendar> inputValues, Calendar targetDatetime) {
    long targetDatetimeInMillis = targetDatetime.getTimeInMillis();
    return Collections.min(inputValues, new Comparator<Calendar>() {
      @Override
      public int compare(Calendar calendar1, Calendar calendar2) {
        long diff1 = Math.abs(targetDatetimeInMillis - calendar1.getTimeInMillis());
        long diff2 = Math.abs(targetDatetimeInMillis - calendar2.getTimeInMillis());
        return Long.compare(diff1, diff2);
      }
    });
  }
  
  // ★ここ★
  private static void sortByNearestDatetime(List<Calendar> inputValues, Calendar targetDatetime) {
    long targetDatetimeInMillis = targetDatetime.getTimeInMillis();
    Collections.sort(inputValues, new Comparator<Calendar>() {
      @Override
      public int compare(Calendar calendar1, Calendar calendar2) {
        long diff1 = Math.abs(targetDatetimeInMillis - calendar1.getTimeInMillis());
        long diff2 = Math.abs(targetDatetimeInMillis - calendar2.getTimeInMillis());
        return Long.compare(diff1, diff2);
      }
    });
  }
}

 出力結果

Input Data : 2016-10-13 00:08:56
Nearest Datetime : 2016-10-12 23:22:00
Result [1] : 2016-10-12 23:22:00
Result [2] : 2016-10-12 20:11:00
Result [3] : 2016-10-21 21:11:00
Result [4] : 2016-11-12 23:11:00
Result [5] : 2016-12-21 19:22:00
Result [6] : 2017-02-21 19:22:00
Result [7] : 2017-02-21 19:22:00
Result [8] : 2016-02-21 19:22:00
Result [9] : 2016-02-21 19:22:00
Result [10] : 2017-12-21 19:22:00
Result [11] : 2015-02-21 19:22:00
Result [12] : 2015-02-21 19:22:00

 参考文献

http://stackoverflow.com/questions/3884644/find-nearest-date-from-a-list

関連記事

日付・時間 について ~ 入門編 ~ https://dk521123.hatenablog.com/entry/2014/11/18/235600
日付・時間 について ~ System.currentTimeMillis / System.nanoTime ~
https://dk521123.hatenablog.com/entry/2017/04/25/223122
日付・時間 について ~ Java8編 ~
https://dk521123.hatenablog.com/entry/2018/02/24/014650