AI Engineering Service

AI Engineering Serviceの公式ブログです。開発者のプライベートな内容を含みます。

【kotlin】日付を任意のフォーマットで書き出す、日付の加減算

f:id:ibarakito:20190821032626p:plain

メモ:
・SimpleDateFormatで指定書式の日付文字列を得られる
・日付の加減算にはCalendarクラスを用いる

SimpleDateFormatのインポート

import java.text.SimpleDateFormat

日付を指定のフォーマットにする

       val format = SimpleDateFormat("yyyy/MM/dd")
       val date = Date()
       timelabel?.text = format.format(date)

日付の計算にはCalendarクラスを使う

            val calendar = Calendar.getInstance()
            calendar.time = date
            //1ヶ月前の日付にする
            calendar.add(Calendar.DAY_OF_MONTH,-1)
            val format = SimpleDateFormat("yyyy/MM/dd")
            //指定フォーマットの文字列にする
            val str : String = format.format(calendar.time)
プライバシーポリシー / お問い合わせ