Rust: chrono庫,date,time及其它_rust

來源:互聯網
上載者:User

Parsing can be done with three methods:

The standard FromStr trait (and parse method on a string) can be used for parsing DateTime, DateTime and DateTime values. This parses what the {:?} (std::fmt::Debug) format specifier prints, and requires the offset to be present.

DateTime::parse_from_str parses a date and time with offsets and returns DateTime. This should be used when the offset is a part of input and the caller cannot guess that. It cannot be used when the offset can be missing. DateTime::parse_from_rfc2822 and DateTime::parse_from_rfc3339 are similar but for well-known formats.

Offset::datetime_from_str is similar but returns DateTime of given offset. When the explicit offset is missing from the input, it simply uses given offset. It issues an error when the input contains an explicit offset different from the current offset.

use chrono::prelude::*;let dt = UTC.ymd(2014, 11, 28).and_hms(12, 0, 9);let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));// method 1assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<UTC>>(), Ok(dt.clone()));assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<UTC>>(), Ok(dt.clone()));assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));// method 2assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),           Ok(fixed_dt.clone()));assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),           Ok(fixed_dt.clone()));assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));// method 3assert_eq!(UTC.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));assert_eq!(UTC.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));// oops, the year is missing!assert!(UTC.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());// oops, the format string does not include the year at all!assert!(UTC.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());// oops, the weekday is incorrect!assert!(UTC.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.