v / vlib / time / time.js.v
73 lines · 63 sloc · 1.91 KB · a74f3171db77de969608c57d7c7bf51733d79f45
Raw
1module time
2
3// now returns the current local time.
4pub fn now() Time {
5 mut res := Time{}
6 #let date = new Date()
7 #res.year.val = date.getFullYear()
8 #res.month.val = date.getMonth()
9 #res.day.val = date.getDay()
10 #res.hour.val = date.getHours()
11 #res.minute.val = date.getMinutes()
12 #res.second.val = date.getSeconds()
13 #res.microsecond.val = date.getMilliseconds() * 1000
14 #res.unix.val = (date.getTime() / 1000).toFixed(0)
15
16 return res
17}
18
19// utc returns the current UTC time.
20pub fn utc() Time {
21 mut res := Time{}
22 #let date = new Date()
23 #res.year.val = date.getUTCFullYear()
24 #res.month.val = date.getUTCMonth()
25 #res.day.val = date.getUTCDay()
26 #res.hour.val = date.getUTCHours()
27 #res.minute.val = date.getUTCMinutes()
28 #res.second.val = date.getUTCSeconds()
29 #res.microsecond.val = date.getUTCMilliseconds() * 1000
30 #res.unix.val = (date.getTime() / 1000).toFixed(0)
31
32 return res
33}
34
35// local returns the local time.
36pub fn (t Time) local() Time {
37 // TODO: Does this actually correct? JS clock is always set to timezone or no?
38 // if it is not we should try to use Intl for getting local time.
39 return t
40}
41
42// sleep suspends the execution for a given duration (in nanoseconds).
43pub fn sleep(dur Duration) {
44 #let now = new Date().getTime()
45 #let toWait = BigInt(dur.val) / BigInt(time__millisecond)
46 #while (new Date().getTime() < now + Number(toWait)) {}
47}
48
49fn time_with_unix(t Time) Time {
50 if t.unix != 0 {
51 return t
52 }
53 mut res := Time{}
54 #res.year.val = t.year.val
55 #res.month.val = t.month.val
56 #res.day.val = t.day.val
57 #res.hour.val = t.hour.val
58 #res.minute.val = t.minute.val
59 #res.second.val = t.second.val
60 #res.microsecond.val = t.microsecond.val
61 #res.unix.val = t.unix.val
62
63 return res
64}
65
66// ticks returns the number of milliseconds since the UNIX epoch.
67// // On Windows ticks returns the number of milliseconds elapsed since system start.
68pub fn ticks() i64 {
69 t := i64(0)
70 #t.val = BigInt(new Date().getTime())
71
72 return t
73}
74