我正在使用这个 rust 码来获取时间戳,但是没有时区的时间:

use std::time::Duration;
use chrono::{DateTime, FixedOffset, Local, NaiveDateTime, TimeZone, Utc};
use diesel::sql_types::Timestamptz;
use rust_wheel::common::util::time_util::get_current_millisecond;
use tokio::time;

#[tokio::main]
async fn main() {
    let trigger_time = (get_current_millisecond() - 35000)/1000;
    let time_without_zone = NaiveDateTime::from_timestamp( trigger_time ,0);
}

时间戳结果是2022-08-30 13:00:15,实际想要的结果是:2022-08-30 21:00:15.然后我try 设置时区:

use std::time::Duration;
use chrono::{DateTime, FixedOffset, Local, NaiveDateTime, TimeZone, Utc};
use diesel::sql_types::Timestamptz;
use rust_wheel::common::util::time_util::get_current_millisecond;
use tokio::time;

#[tokio::main]
async fn main() {
    let trigger_time = (get_current_millisecond() - 35000)/1000;
    let time_without_zone = NaiveDateTime::from_timestamp( trigger_time ,0);

    let tz_offset = FixedOffset::east(8 * 3600);
    let date_time: DateTime<Local> = Local.from_local_datetime(&time_without_zone).unwrap();
    print!("{}",date_time);

    let dt_with_tz: DateTime<FixedOffset> = tz_offset.from_local_datetime(&time_without_zone).unwrap();
    print!("{}",dt_with_tz);
}

结果是2022-08-30 13:00:15 +08:00.可以获得带有时区的时间戳吗?我该怎么办?我的意思是得到这样的时间戳格式2022-08-30 21:00:15.

推荐答案

结果是2022-08-30 13:00:15+08:00.可以获得带有时区的时间戳吗?我该怎么办?我的意思是得到这样的时间戳格式:2022-08-30 21:00:15.

你的时间戳是(我假设)UTC,所以这是你应该告诉Chrono的:

    let time_without_zone = NaiveDateTime::from_timestamp(timestamp, 0);
    // 2009-02-13 23:31:30
    let zoned: DateTime<FixedOffset> = DateTime::from_utc(time_without_zone, FixedOffset::east(8 * 3600));
    // 2009-02-14 07:31:30 +08:00

然后,您可以使用naive_local()来获取本地时间的简单(无时区)视图:

    zoned.naive_local()
    2009-02-14 07:31:30

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=941668e1e10930b0e9a6ede7e79fb0c1

警告:我不确定entirely是否naive_local()是正确的调用,normally在chrono中,"本地"时区是为运行程序的机器配置的时区(或类似的东西),但对于naive_local来说,似乎只是应用了时区,并将结果作为一个简单的日期时间返回.这就是你想要的,但我觉得有点可疑.我找不到更好的电话了.

Rust相关问答推荐

什么样的 struct 可以避免使用RefCell?

如何装箱生命周期相关联的两个对象?

在泛型 struct 的字段声明中访问关联的Conant

铁 rust 干线无法使用PowerShell获取环境变量

避免在Collect()上进行涡鱼类型的涂抹,以产生<;Vec<;_>;,_>;

关于 map 闭合求和的问题

Rust编译器似乎被结果类型与anyhow混淆

Rust ndarray:如何从索引中 Select 数组的行

如何设置activx websocket actorless的消息大小限制?

是否可以在不直接重复的情况下为许多特定类型实现一个函数?

存储返回 impl Trait 作为特征对象的函数

当锁被释放时,将锁包装到作用域中是否会发生变化?

如何在 Rust 中将 Vec> 转换为 Vec>?

为什么 File::read_to_end 缓冲区容量越大越慢?

如何将参数传递给Rust 的线程?

LinkedList::drain_filter::drop 中 DropGuard 的作用是什么?

将一片字节复制到一个大小不匹配的数组中

以下打印数组每个元素的 Rust 代码有什么问题?

返回引用的返回函数

为什么在使用 self 时会消耗 struct 而在解构时不会?