java.text.SimpleDateFormat #parse在Scala和Clojure之间有不同的行为

时间:2017-08-17 22:47:54

标签: java scala datetime clojure

我正在尝试使用PDTjava.util.Date字符串分配给SimpleDateFormat

Scala,为我提供正确的格式PDTUTC-07:00,无论是否设置timeZone,因为我的os timeZone为"America/Los_Angeles"

scala> import java.util.TimeZone
import java.util.TimeZone

scala> import java.util.Date
import java.util.Date

scala> import java.text.SimpleDateFormat
import java.text.SimpleDateFormat

scala> TimeZone.getDefault
res0: java.util.TimeZone = 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]]

scala> val df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
df: java.text.SimpleDateFormat = java.text.SimpleDateFormat@fe8c5ede

scala> df.parse("2017-10-28T23:59:59-07:00")
res1: java.util.Date = Sat Oct 28 23:59:59 PDT 2017

但Clojure以UTC格式(:UTC-00:00)解析日期,

没有.setTimeZone

aws-creds.core=> (import 'java.util.TimeZone)
java.util.TimeZone

aws-creds.core=> (TimeZone/getDefault)
#object[sun.util.calendar.ZoneInfo 0x28ce2a1 "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]]"]

aws-creds.core=> (import 'java.util.Date)
java.util.Date

aws-creds.core=> (import 'java.text.SimpleDateFormat)
java.text.SimpleDateFormat

aws-creds.core=> (let [df (new SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ssXXX" )]
            #_=>   (print (.parse df "2017-10-28T23:59:59-07:00")))
#inst "2017-10-29T06:59:59.000-00:00"nil

.setTimeZoneAmerica/Los_Angeles的行为相同,

aws-creds.core=> (let [df (new SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ssXXX" )]
            #_=>   (.setTimeZone df (TimeZone/getTimeZone "America/Los_Angeles"))
            #_=>   (print (.parse df "2017-10-28T23:59:59-07:00")))
#inst "2017-10-29T06:59:59.000-00:00"nil

这很奇怪,因为在这两种情况下我都在使用java.text.SimpleDateFormat。好奇为什么SimpleDateFormat#parse scala以PDT格式存储日期,而UTC格式的clojure存储?

1 个答案:

答案 0 :(得分:7)

看起来Clojure REPL只是以UTC格式打印日期。

如果您在日期调用toString(),它会打印日期与Scala REPL完全相同(我相信在打印对象时会隐式调用toString),并且在系统时区中:

user=> (let [df (new SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ssXXX" )]
  #_=>   (print (.toString (.parse df "2017-10-28T23:59:59-07:00"))))
Sat Oct 28 23:59:59 PDT 2017nil