如何使用Chrono从NaiveDate转到特定的TimeZone? [英] How do I go from a NaiveDate to a specific TimeZone with Chrono?
问题描述
我正在使用 chrono crate 来解析Rust中的日期和时间。日期和时间来自网站的日期和时间来自页面的不同部分。
I am parsing dates and times in Rust using the chrono crate. The dates and times are from a website in which the date and time are from different sections of the page.
日期以格式显示%d /%m /%Y
(例如:27/08/2018)。时间仅显示小时(例如:12、10、21等)
The date is shown in the format %d/%m/%Y
(example: 27/08/2018). The time is shown with only the hour (example: 12, 10, 21, etc.)
我想将这些日期时间存储为UTC,以便可以计算剩余时间直到现在为止以给定的日期时间以时区不可知的方式。我知道这些日期时间来自(巴黎时间)。
I want to store these datetimes as UTC so that I can compute time remaining until a given datetime from now in a "timezone agnostic" way. I know which timezone these datetimes are from (Paris time).
我从日期输入中创建了 NaiveDate
(这是一个正在进行中的工作,因此尚无错误处理):
I created a NaiveDate
from the date input (this is a work in progress so there's no error handling yet):
let naive_date = NaiveDate::parse_from_str(date, "%d/%m/%Y").unwrap()
从那时起,考虑到我的小时数,获取UTC DateTime
的最佳方法是什么?
From that point on, what would be the best way to get the UTC DateTime
, given that I have a string with the hour?
我迷失在各种 TimeZone
/ Offset
特质,不知道我应该使用 Local
还是 FixedOffset
然后转换为 Utc
。
I am lost in the various TimeZone
/Offset
traits, and do not know if I should use a Local
, or FixedOffset
and then convert to Utc
.
推荐答案
可以改进Chrono文档,以使其更容易找到如何做这些事情。
The Chrono documentation could probably be improved to make it easier to find how to do these things.
假设这是您的起点:
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
// The date you parsed
let date = NaiveDate::from_ymd(2018, 5, 13);
// The known 1 hour time offset in seconds
let tz_offset = FixedOffset::east(1 * 3600);
// The known time
let time = NaiveTime::from_hms(17, 0, 0);
// Naive date time, with no time zone information
let datetime = NaiveDateTime::new(date, time);
然后可以使用 FixedOffset
构造 DateTime
:
let dt_with_tz: DateTime<FixedOffset> = tz_offset.from_local_datetime(&datetime).unwrap();
如果需要将其转换为 DateTime< Utc>
,您可以执行以下操作:
If you need to convert it to a DateTime<Utc>
, you can do this:
let dt_with_tz_utc: DateTime<Utc> = Utc.from_utc_datetime(&dt_with_tz.naive_utc());
这篇关于如何使用Chrono从NaiveDate转到特定的TimeZone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!