2020-02-10 05:19:39 +01:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2020-03-26 04:50:20 +01:00
|
|
|
use crate::define_newtype;
|
2020-06-15 06:14:18 +02:00
|
|
|
use chrono::prelude::*;
|
2020-04-30 01:33:02 +02:00
|
|
|
use lazy_static::lazy_static;
|
|
|
|
use std::env;
|
2020-02-10 05:19:39 +01:00
|
|
|
use std::time;
|
|
|
|
|
2020-03-26 04:50:20 +01:00
|
|
|
define_newtype!(TimestampSecs, i64);
|
|
|
|
define_newtype!(TimestampMillis, i64);
|
2020-03-26 03:59:51 +01:00
|
|
|
|
|
|
|
impl TimestampSecs {
|
|
|
|
pub fn now() -> Self {
|
|
|
|
Self(elapsed().as_secs() as i64)
|
|
|
|
}
|
2020-06-02 05:23:01 +02:00
|
|
|
|
|
|
|
pub fn elapsed_secs(self) -> u64 {
|
|
|
|
(Self::now().0 - self.0).max(0) as u64
|
|
|
|
}
|
2020-06-15 06:14:18 +02:00
|
|
|
|
|
|
|
/// YYYY-mm-dd
|
|
|
|
pub(crate) fn date_string(self, offset: FixedOffset) -> String {
|
|
|
|
offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string()
|
|
|
|
}
|
2020-02-10 05:19:39 +01:00
|
|
|
}
|
2020-03-05 05:55:03 +01:00
|
|
|
|
2020-03-26 03:59:51 +01:00
|
|
|
impl TimestampMillis {
|
|
|
|
pub fn now() -> Self {
|
|
|
|
Self(elapsed().as_millis() as i64)
|
|
|
|
}
|
2020-06-15 06:14:18 +02:00
|
|
|
|
|
|
|
pub fn as_secs(self) -> TimestampSecs {
|
|
|
|
TimestampSecs(self.0 / 1000)
|
|
|
|
}
|
2020-03-22 04:17:00 +01:00
|
|
|
}
|
|
|
|
|
2020-04-30 01:33:02 +02:00
|
|
|
lazy_static! {
|
|
|
|
static ref TESTING: bool = env::var("SHIFT_CLOCK_HACK").is_ok();
|
2020-03-22 04:17:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn elapsed() -> time::Duration {
|
2020-04-30 01:33:02 +02:00
|
|
|
if *TESTING {
|
|
|
|
// shift clock around rollover time to accomodate Python tests that make bad assumptions.
|
|
|
|
// we should update the tests in the future and remove this hack.
|
|
|
|
let mut elap = time::SystemTime::now()
|
|
|
|
.duration_since(time::SystemTime::UNIX_EPOCH)
|
|
|
|
.unwrap();
|
|
|
|
let now = Local::now();
|
|
|
|
if now.hour() >= 2 && now.hour() < 4 {
|
|
|
|
elap -= time::Duration::from_secs(60 * 60 * 2);
|
|
|
|
}
|
|
|
|
elap
|
|
|
|
} else {
|
|
|
|
time::SystemTime::now()
|
|
|
|
.duration_since(time::SystemTime::UNIX_EPOCH)
|
|
|
|
.unwrap()
|
2020-03-22 04:17:00 +01:00
|
|
|
}
|
2020-03-05 05:55:03 +01:00
|
|
|
}
|