19
21

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.

java.sql.*をorg.joda.time.*に変換

Last updated at Posted at 2013-08-29

java.sqlの時間を表すクラスの使えなさにイラッと来たので、joda-timeに変換して使うことにした。

注意点

これらの単純な方式では出力される際に変換が実施されるだけです。
そのため、比較演算でのフィルタ query.filter(_.dateTime <= targetDateTime) などが使えないのが欠点です。
より丁寧に実装する場合はtototoshi/slick-joda-mapperをオススメします。

実装

以下はScalaでの記述例。Javaの場合は、まぁ何となくわかると思うんで読み替えてください。

import java.sql.{Timestamp,Date,Time}
import org.joda.time.{DateTime,LocalDate,LocalTime,DateTimeZone}

java.sql.Timestamp <-> org.joda.time.DateTime

def dateTimeToSqlTimestamp: DateTime => Timestamp = { dt => new Timestamp(dt.getMillis) }
def sqlTimestampToDateTime: Timestamp => DateTime = { ts => new DateTime(ts.getTime) }

java.sql.Date <-> org.joda.time.LocalDate

def localDateToSqlDate: LocalDate => Date = { ld => new Date(ld.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis) }
def sqlDateToLocalDate: Date => LocalDate = { d  => new LocalDate(d.getTime) }

java.sql.Time <-> org.joda.time.LocalTime

def localTimeToSqlTime: LocalTime => Time = { lt => new Time(lt.toDateTimeToday.getMillis) }
def sqlTimeToLocalTime: Time => LocalTime = { t  => new LocalTime(t, DateTimeZone.UTC) }

使用例

Scalaの場合、例えばSlickを使うとORMでの自動変換が可能。

Slick 1.0.x

implicit def timestampMapper =
  MappedTypeMapper.base[DateTime,Timestamp](dateTimeToSqlTimestamp, sqlTimestampToDateTime)

Slick 2.0.x

implicit def timestampMapper =
  MappedColumnType.base[DateTime,Timestamp](dateTimeToSqlTimestamp, sqlTimestampToDateTime)
19
21
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
19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?