[Kotlin]今日の日付のみを取得するには?

Kotlin

どうも、ちょげ(@chogetarou)です。

今日の日付を時刻なしで取得する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

今日の日付のみを取得する方法は、2つあります。

LocalDate

1つは、LocalDateを使う方法です。

まず、java.time.LocalDateをインポートします。

import java.time.LocalDate;

そして、LocalDateからnow()を呼び出します。

val currentDate = LocalDate.now();

上記のLocalDate.now()は、今日の日付をLocalDateとして取得します。

使用例

import java.time.LocalDate;

fun main() {
    val currentDate = LocalDate.now();
   
    println(currentDate);
}
出力:
2022-08-25

SimpleDateFormat

もう1つは、SimpleDateFormatを使う方法です。

まず、SimpleDateFormatとDateをインポートします。

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

次に、SimpleDateFormatをインスタンス化します。

インスタンス化の際、引数に日付のフォーマットを指定します。

そして、SimpleDateFomatのインスタンスからformat()を呼び出します。

format()の引数にDate()を指定します。

val sdf = SimpleDateFormat("フォーマット");
val currentDate : String = sdf.format(Date());

上記のformat()は、今日の日付を文字列として取得します。

使用例

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

fun main() {
    val sdf = SimpleDateFormat("yyyy年MM月dd日");
    val currentDate : String = sdf.format(Date());
   
    println(currentDate);
}
出力:
2022年08月25日
スポンサーリンク

まとめ

今日の日付のみを取得する方法は、次の2つです。

  • LocalDateを使う方法
    val currentDate = LocalDate.now();
  • SimpleDateFormatを使う方法
    val sdf = SimpleDateFormat("フォーマット");
    val currentDate : String = sdf.format(Date());

コメント

タイトルとURLをコピーしました