4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

目的

Redisに時間を書き込んでやりとりする場合、時間を文字列に変換する必要があるのですが、時刻表現のフォーマットがバラバラなのが嫌なので、unixtimestampを使いたいです。
時刻はchronoのDateTimeを使います。

プログラム

Cargo.toml
[package]
name = "unixtimestamp_test"
version = "0.1.0"
edition = "2018"

[dependencies]
chrono = "^0.4"
main.rs
use chrono::prelude::*;

fn parse_str_to_utc(src: &str) -> DateTime<Utc> {
    let mut iter = src.split(".");
    let secs =  iter.next().unwrap_or("0").parse().unwrap_or(0);
    let nanos = iter.next().unwrap_or("0").parse().unwrap_or(0);
    Utc.timestamp(secs, nanos)
}

fn parse_utc_to_str(src: &DateTime<Utc>) -> String {
    format!("{}.{}", src.timestamp(), src.timestamp_subsec_nanos())
}

fn main() {
    let now: DateTime<Utc> = Utc::now();
    let text = parse_utc_to_str(&now);
    let now2 = parse_str_to_utc(&text);
    assert_eq!(now, now2);

    println!("{}", now);
    println!("{}", text);
    println!("{}", parse_str_to_utc("0"));
    println!("{}", parse_str_to_utc("1.1"));
    println!("{}", parse_str_to_utc("1.100000000"));
}
2019-12-02 23:56:41.596503200 UTC
1575331001.596503200
1970-01-01 00:00:00 UTC
1970-01-01 00:00:01.000000001 UTC
1970-01-01 00:00:01.100 UTC
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?