java中的時間轉換(二)(SimpleDateFormat)

SimpleDateFormat

  1. 創建SimpleDateFormat時即可指定各種時間格式
//Demo
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1. format() 把時間轉化爲對應格式的字符串
  2. parse() 把對應格式的字符串轉成Date對象
  val sdf: SimpleDateFormat = new SimpleDateFormat("yyyyMMdd")
  val date = new Date()
  val timeLong = date.getTime

  println("String 轉 Date:  " + sdf.parse("20080101"))
  println("Long類型 轉 String:  " + sdf.format(timeLong))
  println("Date類型 轉 String:  " + sdf.format(date))

在這裏插入圖片描述
SimpleDateFormat 還有其它日期格式,可以隨意玩

  val sdf_date: SimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd")
  val sdf_seconds: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

  println(sdf_date.parse("2019/06/28"))
  println(sdf_seconds.parse("2019-06-28 14:20:00"))

  println(sdf_date.format(date))
  println(sdf_seconds.format(date))

運行效果圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章