scala SimpleDateFormat

SimpleDateFormat函数的继承关系

Java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.DateFormat
                   |
                   +----java.text.SimpleDateFormat 

SimpleDateFormat函数语法

 G 年代标志符
 y 年
 M 月
 d 日
 h 时 (12小时制)
 H 时 (24小时制)
 m 分
 s 秒
 S 毫秒
 E 星期几
 D 一年中的第几天
 F 一月中第几个星期几(1~7号算第一个星期,以此类推)
 w 一年中第几个星期(按正常星期计算)
 W 一月中第几个星期(按正常星期计算)
 a 上午 / 下午 标记符
 k 时 在一天中 (1~24)
 K 时 在上午或下午 (0~11)
 z 时区

示例

import java.text.SimpleDateFormat
import java.util.Calendar

object testCalendar {

  def main(args: Array[String]): Unit = {
    val date: String = "2020-09-08"
    println(formatDate(date, 0))
    println(formatDate(date, 1))
    println(formatDate(date, 2))
  }

  def formatDate(date: String, cutDay: Int): String = {
    val splitDate: Array[String] = date.split("-")
    val year = splitDate(0).toInt
    val month = splitDate(1).toInt - 1
    val day = splitDate(2).toInt
    val cal: Calendar = Calendar.getInstance()
    cal.set(year, month, day)
    cal.add(Calendar.DATE, -cutDay)
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime)
  }
}

输出:

2020-09-08 10:19:34
2020-09-07 10:19:34
2020-09-06 10:19:34
posted @ 2020-09-04 10:06  JunCode  阅读(534)  评论(0编辑  收藏  举报