LoginSignup
0
0

(java silver) API(LocalDateTime)

Posted at

JavaSilverでメモしたところ備忘録として残しておこうと思います。

LocalDataTimeクラス

  • immutable(不変)なオブジェクト(callenderクラスはmmutable)、下記の処理で分かる通りLocalDateTimeクラスでは2021年に変更後も変わらない
import java.time.LocalDataTime;
import java.util.calender;

public class Test {
    public static void main(String[] args){
        LocalDateTime day = LocalDateTime.of(2020,1,1,0,0,0,);
        System.out.println(day);//2020-01-01T00:00
        day.withYear(2021);
        System.out.println(day);//2020-01-01T00:00
        
    }
}

  • 月が1から始まる(calenderクラスは0から)

LocalDateTimeクラスのメソッド

  • nowメソッドで現在の時刻を取得

LocalDateTime ld = LocalDateTime.now(); //現在の時刻取得

  • ofメソッドで日付を指定してオブジェクトを作成

  • parseメソッドで文字列から日付のオブジェクトを変更する

  • 時間の減産や加算のメソッド

概要 メソッド名
年を加算 plusYears(long years)
月を加算 plusMonths(long months)
日を加算 plusDays(long days)
時を加算 plusHours(long hours)
分を加算 plusMinutes(long minutes)
秒を加算 plusSeconds(long seconds)

概要 メソッド名
年を減算 minusYears(long years)
月を減算 minusMonths(long months)
日を減算 minusDays(long days)
時を減算 minusHours(long hours)
分を減算 minusMinutes(long minutes)
秒を減算 minusSeconds(long seconds)

フォーマット

  • LocalDateTimeクラスはDateTimeFormatterクラスを使いフォーマットの指定を行う
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test{
    public static void main(String[] args){
        localDateTime ld = localDateTime.of(2020,1,1,0,0,0);
        DateTimeFormatter dtf = DataTimeFormatter.ofPattern(""yyyy-MM-dd HH:mm:ss");
        System.out.println(ld.format(dtf)); //2020-01-01 00:00:00
}

存在しない日付を指定した場合はjava.time.DateTimeExeptionの実行時エラーが発生する

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