Skip to content

Commit 1d266e8

Browse files
authored
Merge pull request #41 from cquiroz/zoneid-fix
Default ZoneId
2 parents ec8c1dc + 394bb12 commit 1d266e8

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

js/src/main/scala/java/util/TimeZone.scala

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,49 @@ import org.threeten.bp.ZoneId
44

55
import scala.util.Try
66

7+
import scala.scalajs.js
8+
import js.annotation._
9+
10+
@js.native
11+
trait DateTimeFormatOptions extends js.Object {
12+
val timeZone: js.UndefOr[String]
13+
}
14+
15+
@js.native
16+
@JSGlobal("Intl.DateTimeFormat")
17+
class DateTimeFormat() extends js.Object {
18+
def resolvedOptions(): DateTimeFormatOptions = js.native
19+
}
20+
721
object TimeZone {
822
final val SHORT = 0
923
final val LONG = 1
1024

1125
private var default: TimeZone = {
12-
Try {
26+
// This is supported since EcmaScript 1
27+
def offsetInMillis: Int = {
1328
val browserDate = new scalajs.js.Date()
14-
val offsetInMillis = browserDate.getTimezoneOffset() * 60 * 1000
15-
val id = browserDate.toTimeString().split(' ')(1).takeWhile(e => e != '+' && e != '-')
29+
browserDate.getTimezoneOffset() * 60 * 1000
30+
}
1631

17-
new SimpleTimeZone(offsetInMillis, id)
18-
} getOrElse {
19-
new SimpleTimeZone(0, "UTC")
32+
def timeZone: String = {
33+
def browserTZ: Try[String] = {
34+
Try {
35+
val browserDate = new scalajs.js.Date()
36+
browserDate.toTimeString().split(' ')(1).takeWhile(e => e != ' ')
37+
}
38+
}
39+
40+
Try {
41+
// First try with the intl API
42+
new DateTimeFormat().resolvedOptions().timeZone.getOrElse(browserTZ.getOrElse("UTC"))
43+
}.orElse {
44+
// If it fails try to parse it from the date string
45+
browserTZ
46+
}.getOrElse("UTC") // Fallback to UTC
2047
}
48+
49+
new SimpleTimeZone(offsetInMillis, timeZone)
2150
}
2251

2352
def getDefault: TimeZone = default

0 commit comments

Comments
 (0)