Monday, 23 October 2017

clojure epoch time to LocalDateTime to UTC

Part 1 - epoch millis to LocalDateTime in machine with PST Zone 


user=> (import java.util.TimeZone)
java.util.TimeZone
user=> (TimeZone/getDefault)
#object[sun.util.calendar.ZoneInfo 0x36a7961e "sun.util.calendar.ZoneInfo[id=\"America/Los_Angeles\",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]"]

user=> (import java.time.ZoneId)
user=> (import java.time.Instant)

user=> (.atZone (Instant/ofEpochMilli (long 1500318045000)) (ZoneId/systemDefault))
#object[java.time.ZonedDateTime 0x386969fa "2017-07-17T12:00:45-07:00[America/Los_Angeles]"]

user=> (.toLocalDateTime (.atZone (Instant/ofEpochMilli (long 1500318045000)) (ZoneId/systemDefault)))
#object[java.time.LocalDateTime 0x778e9284 "2017-07-17T12:00:45"]

Same epoch millis on a machine with UTC Zone, 

scala> import java.time.Instant
scala> import java.util.TimeZone

scala> TimeZone.getDefault
res9: java.util.TimeZone = sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]

scala> Instant.ofEpochMilli(1500318045000l).atZone(ZoneId.systemDefault()).toLocalDateTime
res10: java.time.LocalDateTime = 2017-07-17T19:00:45

// to milis to UTC
scala> Instant.ofEpochMilli(1500318045000l).atZone(ZoneId.of("UTC")).toInstant.toString
res36: String = 2017-07-17T19:00:45Z

Part 2 - Converting date-string to LocalDateTime and ZonedDateTime

user=> (import java.time.format.DateTimeFormatter)
user=> (import java.time.ZoneId)
user=> (import java.util.TimeZone)
user=> (import java.time.LocalDateTime)

(let [formatter  (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm")
       localDate   (LocalDateTime/parse "2017-01-28T04:00" formatter)
       myZone     (ZoneId/of "America/Chicago")
       zonedDate (.atZone localDate myZone)
       instant     (.toInstant zonedDate)]
       (print (.toString instant)))

2017-01-28T10:00:00Z

No comments:

Post a Comment