🕧

【Android】ThreeTenAbp でミリ秒を除外する

2021/05/24に公開

build.gradle

dependencies {
    def threeTenAbpVersion = '1.3.0'
    implementation "com.jakewharton.threetenabp:threetenabp:$threeTenAbpVersion"
}

MainActivity.kt

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.jakewharton.threetenabp.AndroidThreeTen
import org.threeten.bp.LocalDateTime
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.temporal.ChronoUnit

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
	// ThreeTenABPを初期化
        AndroidThreeTen.init(this)
	// truncatedTo(ChronoUnit.SECONDS)で秒以下を切り捨て
        val localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_DATE_TIME)
        Log.d("ThreeTen", localDateTime)
	
        val offsetDateTime = OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_DATE_TIME)
        Log.d("ThreeTen", offsetDateTime)
    }
}

出力結果

D/ThreeTen: 2021-05-24T16:31:28
D/ThreeTen: 2021-05-24T16:31:28+09:00

Discussion