1use chrono::Utc;
2use lazy_static::lazy_static;
3use sea_orm::entity::prelude::*;
4use time::macros::offset;
5
6lazy_static! {
7 static ref EAST_8: chrono::FixedOffset = chrono::FixedOffset::east_opt(8 * 3600).unwrap();
8}
9
10fn east_8_zone() -> &'static chrono::FixedOffset {
11 &EAST_8
12}
13
14fn from_utc_to_east_8(
15 utc: &chrono::DateTime<chrono::Utc>,
16) -> chrono::DateTime<chrono::FixedOffset> {
17 utc.with_timezone(east_8_zone())
18}
19
20pub fn get_current_time() -> chrono::DateTime<chrono::Utc> {
21 chrono::Utc::now()
22}
23
24pub fn get_current_time_east_8() -> chrono::DateTime<chrono::FixedOffset> {
25 from_utc_to_east_8(&get_current_time())
26}
27
28pub fn get_current_time_east_8_str() -> String {
29 get_current_time_east_8()
30 .format("%Y-%m-%d %H:%M:%S")
31 .to_string()
32}
33
34pub fn get_current_datetime() -> DateTime {
35 let dt: String = get_current_time_east_8_str();
36 DateTime::parse_from_str(&dt, "%Y-%m-%d %H:%M:%S").unwrap()
37}
38
39pub fn get_current_day_str() -> String {
40 get_current_time_east_8().format("%Y-%m-%d").to_string()
41}
42
43pub fn get_current_day() -> Date {
44 let dt: String = get_current_day_str();
45 Date::parse_from_str(&dt, "%Y-%m-%d").unwrap()
46}
47
48pub fn get_db_utc_datetime() -> anyhow::Result<chrono::DateTime<Utc>> {
49 let now: time::OffsetDateTime = time::OffsetDateTime::now_utc().to_offset(offset!(+8));
50 let now_timestamp = now.unix_timestamp_nanos();
51 if let Some(utc_time) = chrono::DateTime::<Utc>::from_timestamp(
52 (now_timestamp / 1000000000) as i64,
53 (now_timestamp % 1000000000) as u32,
54 ) {
55 Ok(utc_time)
56 } else {
57 Err(anyhow::anyhow!("get db utc timestamp with error"))
58 }
59}