1 /**
2  * Proleptic Gregorian calendar: timestamp
3  *
4  * Copyright: Maxim Freck, 2016–2017.
5  * Authors:   Maxim Freck <maxim@freck.pp.ru>
6  * License:   $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7  */
8 module pgc.timestamp;
9 
10 public import pgc.date;
11 public import pgc.exception;
12 public import pgc.time;
13 
14 alias Timestamp = ulong;
15 
16 /***********************************
17  * Returns: Timestamp ulong for a given date and time
18  *
19  * Params:
20  *  date = Date uint
21  *  time = Time uint
22  *
23  * See_Also: `pgc.date.mkDate`, `pgc.time.mkTime`
24  */
25 pure nothrow Timestamp mkTimestamp(Date date, Time time) @safe @nogc
26 {
27 	return ( (cast(ulong)(date) << 32) | time );
28 }
29 
30 /***********************************
31  * Returns: Date uint for a given timestamp
32  *
33  * Params:
34  *  stamp = timestamp
35  */
36 pure nothrow Date date(Timestamp stamp) @safe @nogc
37 {
38 	return cast(Date)(stamp >> 32);
39 }
40 
41 /***********************************
42  * Returns: Time uint for a given timestamp
43  *
44  * Params:
45  *  stamp = timestamp
46  */
47 pure nothrow Time time(Timestamp stamp) @safe @nogc
48 {
49 	return cast(Time)(stamp);
50 }
51 
52 version(Posix) {
53 	import core.sys.posix.sys.time: gettimeofday, gmtime, localtime, timeval;
54 
55 	/***********************************
56 	 * Returns: the current timestamp in UTC
57 	 */
58 	Timestamp ThisMomentUTC()
59 	{
60 		timeval time;
61 		gettimeofday(&time, null);
62 		auto tm = gmtime(&time.tv_sec);
63 		return mkTimestamp(
64 			mkDate(tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900),
65 			mkTime(tm.tm_hour, tm.tm_min, tm.tm_sec, cast(int)(time.tv_usec/31))
66 		);
67 	}
68 
69 	/***********************************
70 	 * Returns: the current timestamp in a local time zone
71 	 */
72 	Timestamp ThisMomentLocal()
73 	{
74 		timeval time;
75 		gettimeofday(&time, null);
76 		auto tm = localtime(&time.tv_sec);
77 		return mkTimestamp(
78 			mkDate(tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900),
79 			mkTime(tm.tm_hour, tm.tm_min, tm.tm_sec, cast(int)(time.tv_usec/31))
80 		);
81 	}
82 }
83 
84 version(Windows) {
85 	import core.sys.windows.windows: GetLocalTime, GetSystemTime, SYSTEMTIME;
86 
87 	/***********************************
88 	 * Returns: the current timestamp in UTC
89 	 */
90 	Timestamp thisMomentUTC()
91 	{
92 		SYSTEMTIME time;
93 		GetSystemTime(&time);
94 		return mkTimestamp(
95 			mkDate(time.wDay, time.wMonth, time.wYear),
96 			mkTime(time.wHour, time.wMinute, time.wSecond, time.wMilliseconds*32)
97 		);
98 	}
99 
100 	/***********************************
101 	 * Returns: the current timestamp in a local time zone
102 	 */
103 	Timestamp thisMomentLocal()
104 	{
105 		SYSTEMTIME time;
106 		GetLocalTime(&time);
107 		return mkTimestamp(
108 			mkDate(time.wDay, time.wMonth, time.wYear),
109 			mkTime(time.wHour, time.wMinute, time.wSecond, time.wMilliseconds*32)
110 		);
111 	}
112 }