1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::ops::Range;

pub use coarsetime::{self, Clock, Duration};
use num_traits::cast::AsPrimitive;

pub const DAY: i64 = 86400;

pub fn now() -> Duration {
  Clock::now_since_epoch()
}

pub fn sec() -> u64 {
  now().as_secs()
}

pub fn ms() -> u64 {
  now().as_millis()
}

pub fn nano() -> u64 {
  now().as_nanos()
}

pub fn min() -> u64 {
  now().as_mins()
}

pub fn hour() -> u64 {
  now().as_hours()
}

pub fn day() -> u64 {
  now().as_days()
}

pub fn sec_month(sec: impl AsPrimitive<i64>) -> i32 {
  use chrono::{DateTime, Datelike, Utc};

  let datetime: DateTime<Utc> = DateTime::from_timestamp(sec.as_(), 0).unwrap();
  let year = datetime.year() - 1970;
  let month = datetime.month() as i32;
  (year * 12 + month) as _
}

pub fn now_month() -> i32 {
  sec_month(sec())
}

/// 前闭后开
pub fn month_sec(month: i32) -> Range<i64> {
  use chrono::{TimeZone, Utc};
  let month = month - 1;
  let year = 1970 + month / 12;
  let month = (month % 12 + 1) as u32;

  let this_month_start = Utc.with_ymd_and_hms(year, month, 1, 0, 0, 0).unwrap();
  let next_month_start = if month == 12 {
    Utc.with_ymd_and_hms(year + 1, 1, 1, 0, 0, 0)
  } else {
    Utc.with_ymd_and_hms(year, month + 1, 1, 0, 0, 0)
  }
  .unwrap();

  let this_month_start_sec = this_month_start.timestamp();
  let this_month_end_sec = next_month_start.timestamp();

  this_month_start_sec..this_month_end_sec
}

pub fn month_day(month: i32) -> Range<i32> {
  let r = month_sec(month);
  ((r.start / DAY) as i32)..((r.end / DAY) as i32)
}

pub fn now_month_day() -> Range<i32> {
  use chrono::{DateTime, Datelike, TimeZone, Utc};
  let now: DateTime<Utc> = DateTime::from_timestamp(sec() as _, 0).unwrap();
  let begin = now.with_day(1).unwrap();
  let begin = begin.timestamp() / 86400;
  let year = now.year();
  let month = now.month();
  let next_month_start = if month == 12 {
    Utc.with_ymd_and_hms(year + 1, 1, 1, 0, 0, 0)
  } else {
    Utc.with_ymd_and_hms(year, month + 1, 1, 0, 0, 0)
  }
  .unwrap();

  let end = next_month_start.timestamp() / 86400;
  (begin as i32)..(end as i32)
}