日期与时间戳转换

 

 

/*
 * Ctrl + Alt + L 自动格式化代码
 * Alt + Enter    自动引用包
 * F8 调试
 * */
object App {

  def main(args: Array[String]): Unit = {
    val dtString = "2020-01-10 10:20:30";
    val sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    val timestamp = dateToTimestamp(dtString, sdf);
    println(timestamp);
    //1578622830000
    val dt = timestampToDate(timestamp, sdf);
    println(dt); //2020-01-10 10:20:30


    val dtString2 = "2019-12-12";
    val sdf2 = new java.text.SimpleDateFormat("yyyy-MM-dd");

    val timestamp2 = dateToTimestamp(dtString2, sdf2);
    println(timestamp2);
    //1576080000000
    val dt2 = timestampToDate(timestamp2, sdf2);
    println(dt2); //2019-12-12
  }

  /**
    * 日期转时间戳
    * val dtString = "2020-01-10 10:20:30";
    * val sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    * **/
  def dateToTimestamp(dtString: String, sdf: java.text.SimpleDateFormat): Long = {
    val dt = sdf.parse(dtString);
    val timestamp = dt.getTime();
    return timestamp;
  }

  /**
    * 时间戳转日期
    * val timestamp = 1578622830000L;
    * val sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    **/
  def timestampToDate(timestamp: Long, sdf: java.text.SimpleDateFormat): String = {
    val dtString = sdf.format(timestamp);
    return dtString;
  }

}

 

posted @ 2020-04-22 01:04  茗::流  阅读(162)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。