java中的時間轉(zhuǎn)換(二)(SimpleDateFormat)

SimpleDateFormat

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

  println("String 轉(zhuǎn) Date:  " + sdf.parse("20080101"))
  println("Long類型 轉(zhuǎn) String:  " + sdf.format(timeLong))
  println("Date類型 轉(zhuǎn) 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))

運行效果圖:


在這里插入圖片描述
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容