time_duration_api
This crate provides a time and duration manipulation API for Rust projects. It aims to simplify common time-related tasks by offering a set of easy-to-use structs and methods.
Overview
The time_duration_api crate provides utilities to handle time and duration operations in Rust. It includes two key structures:
Time: A struct for working with time, offering methods for getting the current time, formatting, manipulating time, and converting between timezones.CustomDuration: A struct for representing durations in a human-readable format, with support for arithmetic operations like addition, subtraction, multiplication, and division.
Features
1. Time Struct
The Time struct represents a specific point in time. It provides the following functionalities:
- Get the current time.
- Format the time into a string using custom formats.
- Add or subtract durations.
- Convert to different timezones.
- Convert from string.
Methods
now(): Returns the current time.format(format: &str): Formats the time using the provided format string.timestamp(): Returns the time as a Unix timestamp (seconds since Jan 1, 1970).add_duration(duration: &CustomDuration): Adds the specified duration to the current time.sub_duration(duration: &CustomDuration): Subtracts the specified duration from the current time.to_timezone(tz: &str): Converts the time to the specified timezone.from_str(time_str: &str, format: &str): Parses a string into aTimeobject using the provided format.
Example Usage
use ;
2. CustomDuration Struct
The CustomDuration struct allows you to represent durations and perform arithmetic operations. It can be initialized using seconds or parsed from a human-readable format (e.g., "1h 30m").
Methods
from_secs(secs: u64): Creates aCustomDurationfrom the specified number of seconds.format_human_readable(): Returns the duration in a human-readable format (e.g.,"1 hour 1 minute").from_str(duration_str: &str): Parses a human-readable duration string into aCustomDuration.- Arithmetic operations:
+: Adds durations.-: Subtracts durations.*: Multiplies the duration by a scalar./: Divides the duration by a scalar.
Example Usage
use ;
How to Use
To use the time_duration_api crate in your Rust project, add it as a dependency in your Cargo.toml:
[]
= "0.1.9"
= "0.4"
= "2.1"
= { = "1.0", = ["derive"] }
Example: Using time_duration_api in main.rs
Your main.rs file should include the following imports:
use ;
After that, you can use the provided methods and structs as shown in the examples above.
Error Handling
The crate uses a custom TimeError enum for error reporting:
- You should use the custom Result type alias to handle these errors gracefully.
pub type Result<T> = std::result::Result<T, TimeError>;
Example:
use Time;
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.