Struct DateTime

Source
pub struct DateTime {
    pub date: Date,
    pub time: Time,
}
Expand description

Represents a combination of date and time.

Fields§

§date: Date§time: Time

Implementations§

Source§

impl DateTime

Source

pub fn now() -> Self

Returns a DateTime instance representing the current date and time.

§Examples
use dev_utils::datetime::DateTime;

let now = DateTime::now();
println!("Current date and time: {}", now);
Examples found in repository?
examples/dlog.rs (line 130)
87fn showcase_log_formatting() {
88    println!(
89        "\n{}",
90        "Enhanced Log Formatting Features:"
91            .style(Style::Bold)
92            .style(Style::Italic)
93    );
94
95    info!("Standard log message");
96
97    // Multi-line log for a simulated data structure
98    let user_data = vec![
99        ("UserID", "12345"),
100        ("Username", "johndoe"),
101        ("Email", "johndoe@example.com"),
102        ("Role", "Admin"),
103    ];
104
105    debug!(
106        "Logging multi-line structured data:\n{}",
107        user_data
108            .iter()
109            .map(|(key, value)| format!("\t{}: {}", key, value))
110            .collect::<Vec<_>>()
111            .join("\n")
112    );
113
114    // Log a long message split across multiple lines
115    info!(
116        "This is a long log message that spans multiple lines for better readability. \
117        It demonstrates how long strings or messages can be split into readable chunks \
118        without breaking the content flow."
119    );
120
121    // Log with colored and styled text
122    let formatted_text = "Formatted".style(Style::Bold).color(GREEN);
123    info!(
124        "Logs can include {} and {} text",
125        formatted_text,
126        "styled".style(Style::Italic).color(MAGENTA)
127    );
128
129    // Log the current timestamp
130    let now = DateTime::now();
131    info!("Current timestamp: {}", now);
132
133    // todo: Add full compatibility with thie multiline log
134    let err_dt = vec![
135        ("Code", "404"),
136        ("Message", "Resource not found"),
137        ("File", file!()),
138    ];
139    // iter over all the data on err_dt and apply the dim style to all the values
140    let err_dt = err_dt
141        .iter()
142        .map(|(key, value)| (key, value.style(Style::Dim)))
143        .collect::<Vec<_>>();
144
145    // Multi-line error simulation
146    error!(
147        "Error on line: {}\n{}",
148        line!(),
149        err_dt
150            .iter()
151            .map(|(key, value)| format!("\t{}: {}", key, value))
152            .collect::<Vec<_>>()
153            .join("\n")
154    );
155
156    // todo: FIX THE ERRORS OCURRED WHEN HANDLING THE MULTILINE LOG...
157    // todo: IT ALSO HAVE SOME ERROR IN WHICH THE STYLE IS APPLIED TO THE WHOLE STRING...
158    // ^ In this case, the "Some new data:" is being styled as a whole string,
159    // ^ not just the "Code: 200" and "Message: You got some successulf penchs"...
160    // same as above but using the str in plain text
161    info!(
162        "Some new data:\n{}{}{}", // Added {} for the file part
163        format!("\tCode: {}\n", "200".style(Style::Underline)), // Style only "200"
164        format!("\tMessage: {}\n\t", "You got some successulf penchs".style(Style::Underline)), // Style only the message
165        file!().style(Style::Bold)
166    );
167}
168
169// = Time to log 10000 messages: 352.6482ms
170// = Average time per log: 35.264µs
171fn showcase_log_performance() {
172    println!(
173        "\n{}",
174        "Log Performance:".style(Style::Bold).style(Style::Italic)
175    );
176
177    let iterations = 10000;
178    let start = std::time::Instant::now();
179
180    (0..iterations).for_each(|i| trace!("Performance test log {}", i));
181
182    let duration = start.elapsed();
183    println!("Time to log {} messages: {:?}", iterations, duration);
184    println!("Average time per log: {:?}", duration / iterations as u32);
185}
186
187fn showcase_log_use_cases() {
188    println!(
189        "\n{}",
190        "Practical Use Cases:"
191            .style(Style::Bold)
192            .style(Style::Italic)
193    );
194
195    // Simulating an application startup
196    info!("Application starting up...");
197    debug!("Initializing modules...");
198    __delay_ms(500);
199    info!("Database connection established");
200    __delay_ms(300);
201    // warn!("Config file not found, using default settings");
202    __delay_ms(200);
203    error!("Failed to load user preferences");
204    info!("Application startup complete");
205
206    // Simulating a function call
207    debug!("Entering function process_data()");
208    __delay_ms(100);
209    trace!("Processing item 1 of 3");
210    __delay_ms(50);
211    trace!("Processing item 2 of 3");
212    __delay_ms(50);
213    trace!("Processing item 3 of 3");
214    __delay_ms(100);
215    debug!("Exiting function process_data()");
216
217    info!("Data processing completed successfully");
218
219    // same as above but now use a tuple to store the macro type, message, and delay, then iterate over it
220
221    // logs.iter().for_each(|(log, msg, delay)| {
222    //     log!("{}", msg);
223    //     __delay_ms(*delay);
224    // });
225}
226
227fn showcase_datetime_features() {
228    println!(
229        "\n{}",
230        "DateTime Features:".style(Style::Bold).style(Style::Italic)
231    );
232
233    // Creating a DateTime instance
234    let now = DateTime::now();
235    info!("Current date and time: {}", now);
236
237    // Creating a custom DateTime
238    let custom_date = Date::new(2023, 12, 31).unwrap();
239    let custom_time = Time::new(23, 59, 59).unwrap();
240    let custom_datetime = DateTime {
241        date: custom_date,
242        time: custom_time,
243    };
244    info!("Custom DateTime: {}", custom_datetime);
245
246    // Parsing a DateTime from a string
247    let parsed_datetime: DateTime = "2023-05-01 12:34:56".parse().unwrap();
248    info!("Parsed DateTime: {}", parsed_datetime);
249
250    // DateTime from timestamp
251    let from_timestamp = DateTime::from_timestamp(1682899200).unwrap();
252    info!("DateTime from timestamp: {}", from_timestamp);
253
254    // Demonstrating error handling
255    match Date::new(2023, 2, 29) {
256        // 29th Feb 2023 (not a leap year)
257        Ok(date) => info!("Valid date: {:?}", date),
258        Err(e) => println!("Invalid date: {}", e),
259        // Err(e) => warn!("Invalid date: {}", e),
260    }
261
262    // Comparing DateTimes
263    info!(
264        "Comparing DateTimes: {} is earlier than {}",
265        "2023-05-01 12:00:00".parse::<DateTime>().unwrap(),
266        "2023-05-01 13:00:00".parse::<DateTime>().unwrap(),
267    );
268
269    // Demonstrating leap year
270    let leap_year = 2024;
271    info!(
272        "Is {} a leap year? {}",
273        leap_year,
274        Date::is_leap_year(leap_year)
275    );
276}
Source

pub fn from_timestamp(timestamp: i64) -> Result<Self, DateTimeError>

Creates a DateTime instance from a Unix timestamp.

§Arguments
  • timestamp - The Unix timestamp (seconds since 1970-01-01 00:00:00 UTC)
§Returns

A Result containing either the valid DateTime or a DateTimeError.

§Examples
use dev_utils::datetime::DateTime;

let dt = DateTime::from_timestamp(1682899200).unwrap();
assert_eq!(dt.to_string(), "2023-05-02 00:00:00");
Examples found in repository?
examples/dlog.rs (line 251)
227fn showcase_datetime_features() {
228    println!(
229        "\n{}",
230        "DateTime Features:".style(Style::Bold).style(Style::Italic)
231    );
232
233    // Creating a DateTime instance
234    let now = DateTime::now();
235    info!("Current date and time: {}", now);
236
237    // Creating a custom DateTime
238    let custom_date = Date::new(2023, 12, 31).unwrap();
239    let custom_time = Time::new(23, 59, 59).unwrap();
240    let custom_datetime = DateTime {
241        date: custom_date,
242        time: custom_time,
243    };
244    info!("Custom DateTime: {}", custom_datetime);
245
246    // Parsing a DateTime from a string
247    let parsed_datetime: DateTime = "2023-05-01 12:34:56".parse().unwrap();
248    info!("Parsed DateTime: {}", parsed_datetime);
249
250    // DateTime from timestamp
251    let from_timestamp = DateTime::from_timestamp(1682899200).unwrap();
252    info!("DateTime from timestamp: {}", from_timestamp);
253
254    // Demonstrating error handling
255    match Date::new(2023, 2, 29) {
256        // 29th Feb 2023 (not a leap year)
257        Ok(date) => info!("Valid date: {:?}", date),
258        Err(e) => println!("Invalid date: {}", e),
259        // Err(e) => warn!("Invalid date: {}", e),
260    }
261
262    // Comparing DateTimes
263    info!(
264        "Comparing DateTimes: {} is earlier than {}",
265        "2023-05-01 12:00:00".parse::<DateTime>().unwrap(),
266        "2023-05-01 13:00:00".parse::<DateTime>().unwrap(),
267    );
268
269    // Demonstrating leap year
270    let leap_year = 2024;
271    info!(
272        "Is {} a leap year? {}",
273        leap_year,
274        Date::is_leap_year(leap_year)
275    );
276}

Trait Implementations§

Source§

impl Clone for DateTime

Source§

fn clone(&self) -> DateTime

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DateTime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DateTime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for DateTime

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string into a DateTime instance.

The expected format is “YYYY-MM-DD HH:MM:SS”.

§Arguments
  • s - The string to parse
§Returns

A Result containing either the parsed DateTime or a DateTimeError.

§Examples
use dev_utils::datetime::DateTime;
use std::str::FromStr;

let dt = DateTime::from_str("2023-05-01 12:34:56").unwrap();
assert_eq!(dt.to_string(), "2023-05-01 12:34:56");
Source§

type Err = DateTimeError

The associated error which can be returned from parsing.
Source§

impl Ord for DateTime

Source§

fn cmp(&self, other: &DateTime) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DateTime

Source§

fn eq(&self, other: &DateTime) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for DateTime

Source§

fn partial_cmp(&self, other: &DateTime) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for DateTime

Source§

impl Eq for DateTime

Source§

impl StructuralPartialEq for DateTime

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.