0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DateAndTime APIを用いた日時取得方法

Posted at

概要

Date and Time APIで以下のパターンをJavaとKotlin(ほぼ同じ)で実装する。

  • 日時の変更
  • 独自フォーマット
  • ISOフォーマット
  • 月初日時
  • 月末日時

実装例

JavaのUtilsクラスだとこちら。

LocalDateUtils.java
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTimeUtils {
    private static final DateTimeFormatter YYYYMM_FORMAT = DateTimeFormatter.ofPattern("yyyyMM");

    // 日時の変更
    public static LocalDateTime getDateTimeAfterOneYear(LocalDateTime dateTime) {
        return dateTime.plusYears(1);
    }

    // 独自フォーマット
    public static String getYearAndMonth(LocalDateTime dateTime) {
        return dateTime.format(YYYYMM_FORMAT);
    }

    // ISOフォーマット 例)2011-12-03
    public static String getIsoLocalDate(LocalDateTime dateTime) {
        return dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
    }

    // 月初日時
    public static LocalDateTime getFirstDayDateTime(LocalDateTime dateTime) {
        return LocalDateTime.of(dateTime.with(TemporalAdjusters.firstDayOfMonth()).toLocalDate(), LocalTime.MIN);
    }

    // 月末日時
    public static LocalDateTime getLastDayDateTime(LocalDateTime dateTime) {
        return LocalDateTime.of(dateTime.with(TemporalAdjusters.lastDayOfMonth()).toLocalDate(), LocalTime.MAX);
    }
}

Kotlinの拡張クラスだとこちら。

LocalDateTime.kt
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters

private val YYYYMM_FORMAT = DateTimeFormatter.ofPattern("yyyyMM")

// 日時の変更
fun LocalDateTime.getDateTimeAfterOneYear(): LocalDateTime = plusYears(1)

// 独自フォーマット
fun LocalDateTime.getYearAndMonth(): String = format(YYYYMM_FORMAT)

// ISOフォーマット 例)2011-12-03
fun LocalDateTime.getIsoLocalDate(): String = format(DateTimeFormatter.ISO_LOCAL_DATE)

// 月初日時
fun LocalDateTime.getFirstDayDateTime(): LocalDateTime = LocalDateTime.of(with(TemporalAdjusters.firstDayOfMonth()).toLocalDate(), LocalTime.MIN)

// 月末日時
fun LocalDateTime.getLastDayDateTime(): LocalDateTime =  LocalDateTime.of(with(TemporalAdjusters.lastDayOfMonth()).toLocalDate(), LocalTime.MAX)
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?