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 5 years have passed since last update.

Java8以前向け: java.util.Calendar型からjava.sql.Date型に変換する方法

Last updated at Posted at 2018-09-20

java.util.Calendar型からjava.sql.Date型に変換する方法を紹介する

  1. 結論
    以下のようにすると変換できる
CalendarToDateTest.java

import java.util.Calendar;
import java.sql.Date;

public class CalendarToDateTest {
    public static void main(String args[]) {
        Calendar calendar = Calendar.getInstance();
        Date date = new Date(calendar.getTime().getTime());
        System.out.println(date);
    }
}

実行結果

$> javac CalendarToDateTest.java
$> java CalendarToDateTest
2018-08-12

2. 解説
    1. CalendarのメソッドgetTime()は、Calendar型のオブジェクト(上記の例でcalendar)の時間値を表すjava.util.Date型のオブジェクトを返す。
    2. java.util.Date型のgetTime()は、java.util.Date型のオブジェクトの時間値の1970年1月1日 00:00:00 GMTからのミリ秒数をlong型で返す。
    3. java.sql.Date型のコンストラクタDate(long date)は、引数で指定されたミリ秒の値を使ってjava.sql.Dateオブジェクトを構築する。
 つまり、java.sql.Dateのコンストラクタの引数に、(Calendar型のオブジェクト).getTime().getTime()を渡すことによって、Calendar型のオブジェクトの時間値を表すjava.sql.date型のオブジェクトを取得することができる。

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?