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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use thiserror::Error;
use crate::digits::{DigitsEn2Ar, DigitsEn2Fa};
pub(crate) const MINUTE: i64 = 60;
pub(crate) const HOUR: i64 = MINUTE * 60;
pub(crate) const DAY: i64 = HOUR * 24;
pub(crate) const MONTH: i64 = DAY * 30;
pub(crate) const YEAR: i64 = DAY * 365;
#[derive(Error, Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum TimeAgoError {
#[error("Wrong datetime format !")]
InvalidDateTimeFormat,
#[error("Unexpected error happened !")]
Unknown,
}
pub enum Timestamp {
String(String),
Integer(i64),
}
impl From<String> for Timestamp {
fn from(datetime_str: String) -> Self {
Timestamp::String(datetime_str)
}
}
impl From<&str> for Timestamp {
fn from(datetime_str: &str) -> Self {
Timestamp::String(datetime_str.to_string())
}
}
impl From<i64> for Timestamp {
fn from(timestamp: i64) -> Self {
Timestamp::Integer(timestamp)
}
}
/// The [TimeDiff] stuct has two main methods: `short_form()` & `long_form()` \
/// the `short_form()` returns a short desciption about time diffrence\
/// - 5 دقیقه قبل
/// - حدود 2 هفته بعد
///
/// the `long_form()` returns a long and exact desciption about time diffrence\
/// - 6 سال و 6 ماه و 10 روز و 12 دقیقه و 37 ثانیه بعد
///
/// also there are more methods to return long_from and short with arabic or persian digits
/// - short_form_fa_digits()
/// - short_form_ar_digits()
/// - long_form_fa_digits()
/// - long_form_ar_digits()
#[derive(PartialEq, Eq, Debug, Clone, Copy, Hash)]
pub struct TimeDiff {
pub years: u32,
pub months: u8,
pub days: u8,
pub hours: u8,
pub minutes: u8,
pub seconds: u8,
pub is_future: bool,
}
impl TimeDiff {
pub fn long_form(&self) -> String {
let mut periods: Vec<String> = Vec::new();
let pre_or_next = self.pre_or_next();
if self.years > 0 {
periods.push(format!("{} سال", self.years))
}
if self.months > 0 {
periods.push(format!("{} ماه", self.months))
}
if self.days > 0 {
periods.push(format!("{} روز", self.days))
}
if self.hours > 0 {
periods.push(format!("{} ساعت", self.hours))
}
if self.minutes > 0 {
periods.push(format!("{} دقیقه", self.minutes))
}
if self.seconds > 0 {
periods.push(format!("{} ثانیه", self.seconds))
}
format!("{} {}", periods.join(" و "), pre_or_next)
}
pub fn short_form(&self) -> String {
let pre_or_next = self.pre_or_next();
if self.years != 0 {
format!("{} {} {} {}", "حدود", &self.years, "سال", pre_or_next)
} else if self.months != 0 {
format!("{} {} {} {}", "حدود", &self.months, "ماه", pre_or_next)
} else if self.days > 7 {
format!("{} {} {} {}", "حدود", &self.days / 7, "هفته", pre_or_next)
} else if self.days != 0 {
format!("{} {} {} {}", "حدود", &self.days, "روز", pre_or_next)
} else if self.hours != 0 {
format!("{} {} {}", &self.hours, "ساعت", pre_or_next)
} else if self.minutes != 0 {
format!("{} {} {}", &self.minutes, "دقیقه", pre_or_next)
} else if self.seconds != 0 {
format!("{} {} {}", &self.seconds, "ثانیه", pre_or_next)
} else {
"اکنون".to_string()
}
}
pub fn short_form_fa_digits(&self) -> String {
self.short_form().digits_en_to_fa()
}
pub fn long_form_fa_digits(&self) -> String {
self.long_form().digits_en_to_fa()
}
pub fn short_form_ar_digits(&self) -> String {
self.short_form().digits_en_to_ar()
}
pub fn long_form_ar_digits(&self) -> String {
self.long_form().digits_en_to_ar()
}
pub fn pre_or_next(&self) -> String {
if self.is_future {
"بعد".to_owned()
} else {
"قبل".to_owned()
}
}
}
/// Converts a valid datetime to timestamp
///
/// # Warning
/// This function is desgined to only works for these date time formats :
///
///
/// - `%Y-%m-%d %H:%M:%S`: Sortable format
/// - `%Y/%m/%d %H:%M:%S`: Sortable format
/// - `%Y-%m-%dT%H:%M:%S%:z`: ISO 8601 with timezone offset
/// - `%Y-%m-%dT%H:%M:%S%.3f%:z`: ISO 8601 with milliseconds and timezone offset
/// - `%a, %d %b %Y %H:%M:%S %z`: RFC 2822 Format
///
///
/// timezone is set with the current timezone of the OS.
///
/// # Examples
///
/// ```
/// use rust_persian_tools::time_diff::convert_to_timestamp;
///
/// assert!(convert_to_timestamp("2023/12/30 12:21:13").is_ok());
/// assert!(convert_to_timestamp("2023/12/30 25:21:13").is_err());
/// ```
pub fn convert_to_timestamp(datetime: impl AsRef<str>) -> Result<i64, TimeAgoError> {
let datetime = datetime.as_ref();
let date_obj = get_date_time(datetime)?;
Ok(date_obj.timestamp())
}
/// Converts datetime to Chrono `DateTime<Local>`
///
/// # Warning
/// This function is desgined to only works for these date time formats :
///
/// - `%Y-%m-%d %H:%M:%S`: Sortable format
/// - `%Y/%m/%d %H:%M:%S`: Sortable format
/// - `%Y-%m-%dT%H:%M:%S%:z`: ISO 8601 with timezone offset
/// - `%Y-%m-%dT%H:%M:%S%.3f%:z`: ISO 8601 with milliseconds and timezone offset
/// - `%a, %d %b %Y %H:%M:%S %z`: RFC 2822 Format
///
/// timezone is set with the current timezone of the OS.
///
/// # Examples
///
/// ```
/// use rust_persian_tools::time_diff::get_date_time;
///
/// assert!(get_date_time("2019/03/18 12:22:14").is_ok());
/// assert!(get_date_time("20192/03/18 12:22:14").is_err());
/// ```
pub fn get_date_time(datetime: impl AsRef<str>) -> Result<DateTime<Local>, TimeAgoError> {
let datetime = datetime.as_ref();
let formats = [
"%Y-%m-%d %H:%M:%S", // Sortable format
"%Y/%m/%d %H:%M:%S", // Sortable format
"%Y-%m-%dT%H:%M:%S%:z", // ISO 8601 with timezone offset
"%Y-%m-%dT%H:%M:%S%.3f%:z", // ISO 8601 with milliseconds and timezone offset
"%a, %d %b %Y %H:%M:%S %z", // RFC 2822 Format
];
for format in formats {
if let Ok(parsed) = NaiveDateTime::parse_from_str(datetime, format) {
// Successfully parsed, convert to timestamp
let datetime_with_timezone = Local.from_local_datetime(&parsed).earliest();
return match datetime_with_timezone {
Some(local_date_time) => Ok(local_date_time),
None => Err(TimeAgoError::Unknown),
};
}
}
Err(TimeAgoError::InvalidDateTimeFormat)
}
/// Returns current timestamp
///
/// # Warning
///
/// timezone is set with the current timezone of the OS.
///
pub fn get_current_timestamp() -> i64 {
let now = Local::now();
now.timestamp()
}
/// datetime argument can be a integer as timestamp or a string as datetime
/// Returns a [TimeDiff] stuct based on how much time is remaining or passed based on the givin datetime\
/// The [TimeDiff] stuct has two methods , `short_form()` & `long_form()` \
///
/// the `short_form()` returns a short desciption about time diffrence\
/// - 5 دقیقه قبل
/// - حدود 2 هفته بعد
///
/// the `long_form()` returns a long and exact desciption about time diffrence\
/// - 6 سال و 6 ماه و 10 روز و 12 دقیقه و 37 ثانیه بعد
///
/// also there are some other methords like `short_form_fa_digits()` or `short_form_ar_digits()` that is the same as `short_form()` but with farsi or arabic digits
///
/// # Warning
/// This function is desgined to only works for these date time formats if you send datetime argument as datetime string :
///
/// - `%Y-%m-%d %H:%M:%S`: Sortable format
/// - `%Y/%m/%d %H:%M:%S`: Sortable format
/// - `%Y-%m-%dT%H:%M:%S%:z`: ISO 8601 with timezone offset
/// - `%Y-%m-%dT%H:%M:%S%.3f%:z`: ISO 8601 with milliseconds and timezone offset
/// - `%a, %d %b %Y %H:%M:%S %z`: RFC 2822 Format
///
/// timezone is set with the current timezone of the OS.
///
/// # Examples
///
/// ```
/// use rust_persian_tools::time_diff::{TimeDiff , time_diff_now};
/// use chrono::{Duration,Local};
///
/// let current_time = Local::now();
/// let due_date = current_time
/// + Duration::weeks(320)
/// + Duration::hours(7)
/// + Duration::minutes(13)
/// + Duration::seconds(37);
/// let formatted_time = due_date.format("%Y-%m-%d %H:%M:%S").to_string();
/// assert_eq!(
/// time_diff_now(formatted_time).unwrap(),
/// TimeDiff {
/// years: 6,
/// months: 1,
/// days: 20,
/// hours: 7,
/// minutes: 13,
/// seconds: 37,
/// is_future: true,
/// }
/// );
///
/// // Example with short_form()
/// let current_time = Local::now();
/// let ten_minutes_ago = current_time - Duration::minutes(10);
/// let formatted_time = ten_minutes_ago.format("%Y-%m-%d %H:%M:%S").to_string(); // create datetime string from 10 minutes ago
/// assert!(time_diff_now(formatted_time).is_ok_and(|datetime| datetime.short_form() == "10 دقیقه قبل"));
/// ```
pub fn time_diff_now(datetime: impl Into<Timestamp>) -> Result<TimeDiff, TimeAgoError> {
let ts_now = get_current_timestamp();
let ts = match datetime.into() {
Timestamp::String(datetime_str) => convert_to_timestamp(datetime_str)?,
Timestamp::Integer(timestamp) => timestamp,
};
let timestamp_diff = ts - ts_now;
Ok(get_time_diff(timestamp_diff))
}
/// start & end arguments can be a integer as timestamp or a string as datetime
/// Returns a [TimeDiff] stuct based on how much time is remaining or passed based on the diffrence between two datetime\
/// The [TimeDiff] stuct has two main methods , `short_form()` & `long_form()` \
/// the `short_form()` returns a short desciption about time diffrence\
/// - 5 دقیقه قبل
/// - حدود 2 هفته بعد
///
/// the `long_form()` returns a long and exact desciption about time diffrence\
/// - 6 سال و 6 ماه و 10 روز و 12 دقیقه و 37 ثانیه بعد
///
/// also there are some other methords like `short_form_fa_digits()` or `short_form_ar_digits()` that is the same as `short_form()` but with farsi or arabic digits
///
/// # Warning
/// This function is desgined to only works for these datetime formats if you send start or end as datetime string:
///
/// - `%Y-%m-%d %H:%M:%S`: Sortable format
/// - `%Y/%m/%d %H:%M:%S`: Sortable format
/// - `%Y-%m-%dT%H:%M:%S%:z`: ISO 8601 with timezone offset
/// - `%Y-%m-%dT%H:%M:%S%.3f%:z`: ISO 8601 with milliseconds and timezone offset
/// - `%a, %d %b %Y %H:%M:%S %z`: RFC 2822 Format
///
/// timezone is set with the current timezone of the OS.
///
/// # Examples
///
/// ```
/// use rust_persian_tools::time_diff::{TimeDiff , time_diff_between};
/// use chrono::{Duration,Local};
///
/// let current_time = Local::now();
/// let start = current_time
/// + Duration::weeks(320)
/// + Duration::hours(7)
/// + Duration::minutes(13)
/// + Duration::seconds(37);
/// let end = (current_time + Duration::weeks(150) + Duration::hours(4)).timestamp();
/// let formatted_time = start.format("%Y-%m-%d %H:%M:%S").to_string();
/// assert_eq!(
/// time_diff_between(formatted_time, end).unwrap(),
/// TimeDiff {
/// years: 3,
/// months: 3,
/// days: 5,
/// hours: 3,
/// minutes: 13,
/// seconds: 37,
/// is_future: false,
/// }
/// );
///
/// // Example with long_form() with persian digits
// let current_time = Local::now();
// let start = current_time
// + Duration::weeks(320)
// + Duration::hours(7)
// + Duration::minutes(13)
// + Duration::seconds(37);
//
// let end = (current_time + Duration::weeks(150) + Duration::hours(4)).timestamp();
//
// let formatted_time = start.format("%Y-%m-%d %H:%M:%S").to_string();
// assert_eq!(
// time_diff_between(formatted_time, end)
// .unwrap()
// .long_form_fa_digits(),
// "۳ سال و ۳ ماه و ۵ روز و ۳ ساعت و ۱۳ دقیقه و ۳۷ ثانیه قبل"
// );
/// ```
pub fn time_diff_between(
start: impl Into<Timestamp>,
end: impl Into<Timestamp>,
) -> Result<TimeDiff, TimeAgoError> {
let ts_start = match start.into() {
Timestamp::String(datetime_str) => convert_to_timestamp(datetime_str)?,
Timestamp::Integer(timestamp) => timestamp,
};
let ts_end = match end.into() {
Timestamp::String(datetime_str) => convert_to_timestamp(datetime_str)?,
Timestamp::Integer(timestamp) => timestamp,
};
let timestamp_diff = ts_end - ts_start;
Ok(get_time_diff(timestamp_diff))
}
fn get_time_diff(timestamp_diff: i64) -> TimeDiff {
let is_future = timestamp_diff > 0;
let mut timestamp_diff = timestamp_diff.abs();
let years: u32 = (timestamp_diff / YEAR) as u32;
timestamp_diff %= YEAR;
let months: u8 = ((timestamp_diff / MONTH) % MONTH) as u8;
timestamp_diff %= MONTH;
let days: u8 = ((timestamp_diff / DAY) % DAY) as u8;
timestamp_diff %= DAY;
let hours: u8 = ((timestamp_diff / HOUR) % HOUR) as u8;
timestamp_diff %= HOUR;
let minutes: u8 = ((timestamp_diff / MINUTE) % MINUTE) as u8;
timestamp_diff %= MINUTE;
let seconds: u8 = timestamp_diff as u8;
TimeDiff {
years,
months,
days,
hours,
minutes,
seconds,
is_future,
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
fn test_time_diff_now() {
let current_time = Local::now();
// let ten_minutes_ago = current_time - Duration::minutes(10);
let formatted_time = current_time.format("%Y-%m-%dT%H:%M:%S%:z").to_string();
assert!(
time_diff_now(formatted_time).is_ok_and(|datetime| datetime.short_form() == "اکنون")
);
}
#[test]
fn test_time_diff_10_min_ago() {
let current_time = Local::now();
let ten_minutes_ago = current_time - Duration::minutes(10);
let formatted_time = ten_minutes_ago.format("%Y-%m-%d %H:%M:%S").to_string();
// dbg!(time_diff(&formatted_time))
assert!(time_diff_now(formatted_time)
.is_ok_and(|datetime| datetime.short_form() == "10 دقیقه قبل"));
}
#[test]
fn test_time_diff_between_to_datetime() {
let current_time = Local::now();
let start = current_time
+ Duration::weeks(320)
+ Duration::hours(7)
+ Duration::minutes(13)
+ Duration::seconds(37);
let end = (current_time + Duration::weeks(150) + Duration::hours(4)).timestamp();
let formatted_time = start.format("%Y-%m-%d %H:%M:%S").to_string();
assert_eq!(
time_diff_between(formatted_time, end).unwrap(),
TimeDiff {
years: 3,
months: 3,
days: 5,
hours: 3,
minutes: 13,
seconds: 37,
is_future: false,
}
);
}
#[test]
fn test_time_diff_between_to_datetime_with_long_format_persian_digits() {
let current_time = Local::now();
let start = current_time
+ Duration::weeks(320)
+ Duration::hours(7)
+ Duration::minutes(13)
+ Duration::seconds(37);
let end = (current_time + Duration::weeks(150) + Duration::hours(4)).timestamp();
let formatted_time = start.format("%Y-%m-%d %H:%M:%S").to_string();
assert_eq!(
time_diff_between(formatted_time, end)
.unwrap()
.long_form_fa_digits(),
"۳ سال و ۳ ماه و ۵ روز و ۳ ساعت و ۱۳ دقیقه و ۳۷ ثانیه قبل"
);
}
#[test]
fn test_time_diff_next_2_weeks() {
let current_time = Local::now();
let ten_minutes_ago = current_time + Duration::weeks(2);
let formatted_time = ten_minutes_ago
.format("%a, %d %b %Y %H:%M:%S %z")
.to_string();
assert!(time_diff_now(formatted_time)
.is_ok_and(|datetime| datetime.short_form() == "حدود 2 هفته بعد"));
}
#[test]
fn test_time_diff_next_3_months() {
let current_time = Local::now();
let ten_minutes_ago = current_time + Duration::days(31 * 3);
let formatted_time = ten_minutes_ago
.format("%Y-%m-%dT%H:%M:%S%.3f%:z")
.to_string();
assert!(time_diff_now(formatted_time)
.is_ok_and(|datetime| datetime.short_form() == "حدود 3 ماه بعد"));
}
#[test]
fn test_time_diff_as_struct() {
let current_time = Local::now();
let due_date = current_time
+ Duration::weeks(320)
+ Duration::hours(7)
+ Duration::minutes(13)
+ Duration::seconds(37);
let formatted_time = due_date.format("%Y-%m-%d %H:%M:%S").to_string();
assert_eq!(
time_diff_now(formatted_time).unwrap(),
TimeDiff {
years: 6,
months: 1,
days: 20,
hours: 7,
minutes: 13,
seconds: 37,
is_future: true,
}
);
}
#[test]
fn test_time_diff_as_long_form() {
let current_time = Local::now();
let due_date =
current_time + Duration::weeks(340) + Duration::minutes(12) + Duration::seconds(37);
let formatted_time = due_date.format("%Y-%m-%d %H:%M:%S").to_string();
assert_eq!(
time_diff_now(formatted_time).unwrap().long_form(),
String::from("6 سال و 6 ماه و 10 روز و 12 دقیقه و 37 ثانیه بعد")
);
}
#[test]
fn test_check_valid_date_time() {
assert!(get_date_time("2019/03/18 12:22:14").is_ok());
assert!(get_date_time("20192/03/18 12:22:14").is_err());
}
}