LoginSignup
22
21

More than 1 year has passed since last update.

Kotlinで文字列を数値、日付文字列を日付(java.util.Date)、日付を文字列(String)に変換する

Last updated at Posted at 2017-11-22

Kotlinで文字列を数値に変更する方法です。また日付文字列をDateに変換、Dateを文字列に変換します。

文字列から数値へ変換する(StringからIntへの変換)

Kotlinの標準ライブラリに文字列から数値へ変換するための拡張関数が用意されていてtoInt、toByte、toBooleanなどが使えます。

val str = "43"
println(str.toInt())

他にも次のような変換用の関数があります。

String型変換関数
fun String.toBoolean(): Boolean
fun String.toByte(): Byte
fun String.toDouble(): Double
fun String.toFloat(): Float
fun String.toInt(): Int
fun String.toLong(): Long
fun String.toShort(): Short

文字列を数値に変換できなかった場合は、NumberFormatExceptionが発生します。

日付を文字列に変換する(DateをStringに変換)

GetNowDate.kt
val df = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
val date = Date()
println(df.format(date))

フォーマット文字列は固定文字列としましたのでExceptionは発生しません。そのためここではtry-catchは不要です。

日付文字列を日付型に変換する(StringをDateに変換)

Stringから数値へ変換するように、StringからDateへ変換する拡張関数toDateを用意します。

DateUtil.kt
import java.text.ParseException
import java.lang.IllegalArgumentException
import java.text.SimpleDateFormat
import java.util.Date

fun String.toDate(pattern: String = "yyyy/MM/dd HH:mm:ss"): Date? {
    val sdFormat = try {
        SimpleDateFormat(pattern)
    } catch (e: IllegalArgumentException) {
        null
    }
    val date = sdFormat?.let {
        try {
            it.parse(this)
        } catch (e: ParseException){
            null
        }
    }
    return date
}

Javaではtry-catchでParseExceptionを処理しなければなりませんでしたが、Kotlinでは例外処理は必須ではないので書いても書かなくてもOKです。
しかしここでは、日付の変換フォーマットと、日付に変換したい文字列のどちらもユーザ入力の可能性を想定しているので、try-catchを行っています。
例外が発生した場合はcatchでnullを返すようにしています。

拡張関数toDateは次のように利用します。

>>> val strDate = "2017/10/24 12:12:12"
>>> println(strDate.toDate())
Tue Oct 24 12:12:12 JST 2017
22
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
22
21