< 返回我的博客

子十 发表于 2021-08-08 09:40

Tags:datetime,serialize,chrono,serde

主要参考:Rustcc网站源码库

在处理数据表中日期相关数据时,Seralize序列化相关操作会报错,提示 DateTime 字段不识别, 查了 rustcc 源码才发现依赖中需要开启相应的feature。特此记录。

1.依赖的库:

[dependencies]
# 日期时间处理 需要开启 serde 特征 支持序列化
chrono = { version = "0.4.19", features = ["serde"] }

# 数据库ORM
diesel = { version = "1.4.4", features = ["postgres", "chrono", "uuid", "r2d2"] }
dotenv = "0.15.0"
serde = { version = "1.0.127", features = ["derive"] }
serde_json = "1.0.66"
uuid = { version = "0.8.2", features = ["serde", "v4"] }

2.创建数据表

CREATE TABLE characters (
    id SERIAL PRIMARY KEY,
    name VARCHAR(128) UNIQUE NOT NULL,
    age INTEGER NOT NULL DEFAULT 0,
    friends VARCHAR NOT NULL DEFAULT '',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)

3.数据表对应的 model

use chrono::{NaiveDateTime};
use serde::{Deserialize, Serialize};

#[derive(Queryable, Serialize, Deserialize, Debug)]
pub struct Characters {
    pub id: i32,
    pub name: String,
    pub age: i32,
    pub friends: String,
    // 这里的 NaiveDateTime 日期格式序列化需要开启相关 features
    pub created_at: NaiveDateTime,
}

4.获取数据

use db::schema::characters;
use db::{get_connection};
use db::models::{Characters, NewCharacter};
use db::schema::characters::dsl::*;
use diesel::QueryDsl;
use diesel::prelude::*;

fn main() {
    let conn = get_connection();

    // 查询年龄大于30的10条数据
    let arr: Vec<Characters> = characters.filter(characters::age.gt(30))
        .limit(10)
        .load::<Characters>(&conn)
        .expect("Loading Error");

    let date_arr = arr.iter()
        .map(|item| {
	    // 数据格式化
            let t = item.created_at.format("%Y-%m-%d %H:%M:%S").to_string();
            println!("{} {}", item.name, t);
            t
        })
        .collect::<Vec<String>>();
}

输出结果类似:

Box 2021-08-05 09:39:34
Bobe 2021-08-05 09:39:34

评论区

写评论

还没有评论

1 共 0 条评论, 1 页