Lobsterrrr Lobsterrrr - 1 month ago 11
Scala Question

How to retrieve the year from a Unix timestamp?

I am using

nscala-time
for scala 2.11:

<dependency>
<groupId>com.github.nscala-time</groupId>
<artifactId>nscala-time_2.11</artifactId>
<version>2.12.0</version>
</dependency>


The goal is to retrieve the year from a Unix timestamp:

val t = "1320904800"
val dt = new DateTime(timestamp.toLong)
dt.getYear.toString


The problem is that it outputs 1970 instead of 2011. What am I doing wrong?

Answer

DateTime constructor assumes millisecond value, and it seems like your input is in seconds (i.e. seconds since 1970/01/01 00:00:00.0) - you should get the right result if you multiply by 1000:

val t = "1320904800"
val dt = new DateTime(t.toLong * 1000)
println(dt.getYear.toString) // 2011
Comments