64056
|
1 |
/* Title: Pure/General/date.scala
|
|
2 |
Author: Makarius
|
|
3 |
|
|
4 |
Date and time, with time zone.
|
|
5 |
*/
|
|
6 |
|
|
7 |
package isabelle
|
|
8 |
|
|
9 |
|
64057
|
10 |
import java.time.{Instant, ZonedDateTime, ZoneId}
|
64056
|
11 |
import java.time.format.{DateTimeFormatter, DateTimeParseException}
|
64059
|
12 |
import java.time.temporal.TemporalAccessor
|
|
13 |
|
|
14 |
import scala.annotation.tailrec
|
64056
|
15 |
|
|
16 |
|
|
17 |
object Date
|
|
18 |
{
|
|
19 |
/* format */
|
|
20 |
|
|
21 |
object Format
|
|
22 |
{
|
64060
|
23 |
def make(fmts: List[DateTimeFormatter], filter: String => String = s => s): Format =
|
64059
|
24 |
{
|
|
25 |
require(fmts.nonEmpty)
|
|
26 |
|
|
27 |
@tailrec def parse_first(
|
|
28 |
last_exn: Option[Throwable], fs: List[DateTimeFormatter], str: String): TemporalAccessor =
|
|
29 |
{
|
|
30 |
fs match {
|
|
31 |
case Nil => throw last_exn.get
|
|
32 |
case f :: rest =>
|
|
33 |
try { ZonedDateTime.from(f.parse(str)) }
|
|
34 |
catch { case exn: DateTimeParseException => parse_first(Some(exn), rest, str) }
|
|
35 |
}
|
|
36 |
}
|
64056
|
37 |
new Format {
|
64059
|
38 |
def apply(date: Date): String = fmts.head.format(date.rep)
|
|
39 |
def parse(str: String): Date =
|
64060
|
40 |
new Date(ZonedDateTime.from(parse_first(None, fmts, filter(str))))
|
64056
|
41 |
}
|
64059
|
42 |
}
|
64056
|
43 |
|
64060
|
44 |
def make_patterns(patterns: List[String], filter: String => String = s => s): Format =
|
|
45 |
make(patterns.toList.map(DateTimeFormatter.ofPattern(_)), filter)
|
|
46 |
|
64059
|
47 |
def apply(patterns: String*): Format =
|
|
48 |
make(patterns.toList.map(DateTimeFormatter.ofPattern(_)))
|
64056
|
49 |
|
|
50 |
val default: Format = apply("dd-MMM-uuuu HH:mm:ss xx")
|
64057
|
51 |
val date: Format = apply("dd-MMM-uuuu")
|
|
52 |
val time: Format = apply("HH:mm:ss")
|
64056
|
53 |
}
|
|
54 |
|
|
55 |
abstract class Format private
|
|
56 |
{
|
|
57 |
def apply(date: Date): String
|
|
58 |
def parse(str: String): Date
|
|
59 |
def unapply(str: String): Option[Date] =
|
|
60 |
try { Some(parse(str)) }
|
|
61 |
catch { case _: DateTimeParseException => None }
|
|
62 |
}
|
64057
|
63 |
|
|
64 |
|
|
65 |
/* date operations */
|
|
66 |
|
|
67 |
def timezone(): ZoneId = ZoneId.systemDefault
|
|
68 |
|
|
69 |
def now(zone: ZoneId = timezone()): Date = new Date(ZonedDateTime.now(zone))
|
|
70 |
|
|
71 |
def apply(t: Time, zone: ZoneId = timezone()): Date =
|
|
72 |
new Date(ZonedDateTime.ofInstant(t.instant, zone))
|
64056
|
73 |
}
|
|
74 |
|
64059
|
75 |
sealed case class Date(rep: ZonedDateTime)
|
64056
|
76 |
{
|
64057
|
77 |
def time: Time = Time.instant(Instant.from(rep))
|
|
78 |
def timezone: ZoneId = rep.getZone
|
|
79 |
|
|
80 |
def format(fmt: Date.Format = Date.Format.default): String = fmt(this)
|
|
81 |
override def toString: String = format()
|
64056
|
82 |
}
|