乐闻世界logo
搜索文章和话题

How to get Timestamp of the current Date and time in Rust

1个答案

1

Getting the timestamp for the current date and time in Rust typically requires using external libraries, as Rust's standard library lacks direct support for date and time operations. Chrono is a widely used library for handling date and time, offering convenient APIs to retrieve and manipulate date and time.

First, add the chrono library to your project by including the following dependency in your Cargo.toml file:

toml
[dependencies] chrono = "0.4"

Next, in your Rust code, utilize the chrono library to obtain the current date and time and convert it to a timestamp. Here is an example:

rust
extern crate chrono; use chrono::{Utc, Local, DateTime}; fn main() { // Get the current UTC time let now_utc: DateTime<Utc> = Utc::now(); println!("Current UTC timestamp: {}", now_utc.timestamp()); // For local time timestamp, use this let now_local: DateTime<Local> = Local::now(); println!("Current local timestamp: {}", now_local.timestamp()); }

In this example, we employ chrono's Utc and Local structures to fetch the current UTC and local time. The timestamp() method returns an i64 value representing the number of seconds elapsed since January 1, 1970 (UTC).

This approach facilitates handling date and time-related tasks in Rust applications, particularly for comparisons, calculations, or conversions. With the chrono library, Rust developers can manage these operations more efficiently.

2024年7月1日 12:55 回复

你的答案