diff --git a/Cargo.lock b/Cargo.lock index a43a0c1..c63d75e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3255,7 +3255,7 @@ dependencies = [ [[package]] name = "web-petting" -version = "0.1.3" +version = "0.1.4" dependencies = [ "chrono", "chrono-tz", diff --git a/src/tz.rs b/src/tz.rs new file mode 100644 index 0000000..e922890 --- /dev/null +++ b/src/tz.rs @@ -0,0 +1,31 @@ +use chrono::TimeZone; +use chrono_tz::Tz; +use cot::db::{Database, Model, query}; + +use crate::models::Setting; + +const DEFAULT_TZ: &str = "UTC"; + +/// Load timezone from the database settings. +pub async fn load_tz(db: &Database) -> Tz { + let key = "timezone".to_string(); + let tz_str = query!(Setting, $key == key) + .get(db) + .await + .ok() + .flatten() + .map(|s| s.value) + .unwrap_or_else(|| DEFAULT_TZ.to_string()); + tz_str.parse::().unwrap_or(Tz::UTC) +} + +/// Current date+time in the configured timezone, returned as NaiveDateTime. +#[allow(dead_code)] +pub fn now_in_tz(tz: Tz) -> chrono::NaiveDateTime { + chrono::Utc::now().with_timezone(&tz).naive_local() +} + +/// Today's date in the configured timezone. +pub fn today_in_tz(tz: Tz) -> chrono::NaiveDate { + chrono::Utc::now().with_timezone(&tz).date_naive() +}