time.rs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::time::UNIX_EPOCH;
  19. use chrono::{NaiveDateTime, Utc};
  20. use darkfi_serial::{SerialDecodable, SerialEncodable};
  21. use serde::{Deserialize, Serialize};
  22. use crate::Result;
  23. /// Wrapper struct to represent [`chrono`] UTC timestamps.
  24. #[derive(
  25. Clone,
  26. Copy,
  27. Debug,
  28. Serialize,
  29. Deserialize,
  30. SerialEncodable,
  31. SerialDecodable,
  32. PartialEq,
  33. PartialOrd,
  34. Eq,
  35. )]
  36. pub struct Timestamp(pub i64);
  37. impl Timestamp {
  38. /// Generate a `Timestamp` of the current time.
  39. pub fn current_time() -> Self {
  40. Self(Utc::now().timestamp())
  41. }
  42. /// Calculates elapsed time of a `Timestamp`.
  43. pub fn elapsed(&self) -> u64 {
  44. let start_time = NaiveDateTime::from_timestamp_opt(self.0, 0).unwrap();
  45. let end_time = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
  46. let diff = end_time - start_time;
  47. diff.num_seconds() as u64
  48. }
  49. /// Increment a 'Timestamp'.
  50. pub fn add(&mut self, inc: i64) {
  51. self.0 += inc;
  52. }
  53. }
  54. impl std::fmt::Display for Timestamp {
  55. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  56. let date = timestamp_to_date(self.0, DateFormat::DateTime);
  57. write!(f, "{}", date)
  58. }
  59. }
  60. #[derive(
  61. Clone,
  62. Copy,
  63. Debug,
  64. Serialize,
  65. Deserialize,
  66. SerialEncodable,
  67. SerialDecodable,
  68. PartialEq,
  69. PartialOrd,
  70. Eq,
  71. )]
  72. pub struct NanoTimestamp(pub i64);
  73. impl NanoTimestamp {
  74. pub fn current_time() -> Self {
  75. Self(Utc::now().timestamp_nanos())
  76. }
  77. }
  78. impl std::fmt::Display for NanoTimestamp {
  79. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  80. let date = timestamp_to_date(self.0, DateFormat::Nanos);
  81. write!(f, "{}", date)
  82. }
  83. }
  84. pub enum DateFormat {
  85. Default,
  86. Date,
  87. DateTime,
  88. Nanos,
  89. }
  90. pub fn timestamp_to_date(timestamp: i64, format: DateFormat) -> String {
  91. if timestamp <= 0 {
  92. return "".to_string()
  93. }
  94. match format {
  95. DateFormat::Date => NaiveDateTime::from_timestamp_opt(timestamp, 0)
  96. .unwrap()
  97. .date()
  98. .format("%-d %b")
  99. .to_string(),
  100. DateFormat::DateTime => NaiveDateTime::from_timestamp_opt(timestamp, 0)
  101. .unwrap()
  102. .format("%H:%M:%S %A %-d %B")
  103. .to_string(),
  104. DateFormat::Nanos => {
  105. const A_BILLION: i64 = 1_000_000_000;
  106. NaiveDateTime::from_timestamp_opt(timestamp / A_BILLION, (timestamp % A_BILLION) as u32)
  107. .unwrap()
  108. .format("%H:%M:%S.%f")
  109. .to_string()
  110. }
  111. DateFormat::Default => "".to_string(),
  112. }
  113. }
  114. pub fn unix_timestamp() -> Result<u64> {
  115. Ok(UNIX_EPOCH.elapsed()?.as_secs())
  116. }