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}
|
|
12 |
|
|
13 |
|
|
14 |
object Date
|
|
15 |
{
|
|
16 |
/* format */
|
|
17 |
|
|
18 |
object Format
|
|
19 |
{
|
|
20 |
def apply(fmt: DateTimeFormatter): Format =
|
|
21 |
new Format {
|
|
22 |
def apply(date: Date): String = fmt.format(date.rep)
|
|
23 |
def parse(str: String): Date = new Date(ZonedDateTime.from(fmt.parse(str)))
|
|
24 |
}
|
|
25 |
|
|
26 |
def apply(pattern: String): Format =
|
|
27 |
apply(DateTimeFormatter.ofPattern(pattern))
|
|
28 |
|
|
29 |
val default: Format = apply("dd-MMM-uuuu HH:mm:ss xx")
|
64057
|
30 |
val date: Format = apply("dd-MMM-uuuu")
|
|
31 |
val time: Format = apply("HH:mm:ss")
|
64056
|
32 |
}
|
|
33 |
|
|
34 |
abstract class Format private
|
|
35 |
{
|
|
36 |
def apply(date: Date): String
|
|
37 |
def parse(str: String): Date
|
|
38 |
def unapply(str: String): Option[Date] =
|
|
39 |
try { Some(parse(str)) }
|
|
40 |
catch { case _: DateTimeParseException => None }
|
|
41 |
}
|
64057
|
42 |
|
|
43 |
|
|
44 |
/* date operations */
|
|
45 |
|
|
46 |
def timezone(): ZoneId = ZoneId.systemDefault
|
|
47 |
|
|
48 |
def now(zone: ZoneId = timezone()): Date = new Date(ZonedDateTime.now(zone))
|
|
49 |
|
|
50 |
def apply(t: Time, zone: ZoneId = timezone()): Date =
|
|
51 |
new Date(ZonedDateTime.ofInstant(t.instant, zone))
|
64056
|
52 |
}
|
|
53 |
|
|
54 |
sealed case class Date private(private[Date] rep: ZonedDateTime)
|
|
55 |
{
|
64057
|
56 |
def time: Time = Time.instant(Instant.from(rep))
|
|
57 |
def timezone: ZoneId = rep.getZone
|
|
58 |
|
|
59 |
def format(fmt: Date.Format = Date.Format.default): String = fmt(this)
|
|
60 |
override def toString: String = format()
|
64056
|
61 |
}
|