我试图在scala中打印日期,但它没有打印正确的值

时间:2018-02-20 17:22:20

标签: scala

我的代码。刚才提到的日期部分。

case class data (id:String, date:String, temp:Int, pressure:Int, humidity:Int)

val date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

val date1=date.toString

var first= new data(id1,date1,temp,press,hum)

我的输出是

date":"java.text.SimpleDateFormat@4f76f1a0"

2 个答案:

答案 0 :(得分:0)

代码中的问题是SimpleDateFormatDate的格式化程序。

首先需要java.util.Date,然后您可以使用格式化程序

来表示字符串
import java.util.Date
import java.text.SimpleDateFormat

val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

val d = new Date()
val dateString = sdf.format(d)

println(dateString)

//output: 2018-02-20 10:00:00

答案 1 :(得分:0)

java.util.Date API有点过时,我强烈反对您不使用它。使用(更加理智)java.time代替。

如果您决定切换到java.time,请参阅以下答案。

代码中的SimpleDateFormat("yyyy-MM-dd HH:mm:ss")仅实例化格式化程序。它不会产生任何日期 格式。字符串“java.text.SimpleDateFormat@4f76f1a0”不是格式正确的日期,它只是格式化程序的标准toString方法的输出。为了获得格式化日期的字符串表示,您必须:

  • 实例化格式化程序
  • 实例化日期
  • 将日期传递给格式化程序

使用java.time,这看起来有点像这样:

import java.time._
import java.time.format._

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val currentDateInUTC = ZonedDateTime.now(ZoneId.of("UTC"))
val date1: String = formatter format currentDateInUTC

println(date1)

打印:

2018-02-20 17:57:28
相关问题