【从头写CAD】第一章 计量单位 第三节 时间类


一、说明

我用时间单位秒(s)作为基准,因为它是国际单位制中的基本单位。数值类型的选择有2种:1、实数(f64),优点是可以兼顾比它小的单位ms(毫秒,千分之一秒)、μs(微秒,百万分之一秒)和ns(纳秒,十亿分之一秒)。缺点是表达不精准,有舍入误差。2、整数(i64),表达精准,可以满足大多数场合要求,特殊场合需要重新定义新类。我选择了后者。


二、代码

/*
* 时间的类Time
** 编制人: $ource
* 修改版次及创建时间:0版完成版(2024年9月5日)
* 修改内容及时间:无
* 待完善问题:无
*/

use std::ops::{Add, Sub, Mul, Div};
#[derive(Debug,PartialEq,PartialOrd,Clone,Copy)]
pub struct Time{
    pub second:i64
}

impl Time{
    pub fn new(second:i64)->Time{
        Time{second}
    }

    fn from_second(second:i64)->Time{
        Time{second:second}
    }
    pub fn from_minute(minute:i64)->Time{
        Time{second:minute*60i64}
    }

    pub fn from_hour(hour:i64)->Time{
        Time{second:hour*3600i64}
    }
    
    pub fn from_day(day:i64)->Time{
        Time{second:day*86400i64}
    }

    pub fn from_time(hour:i64,minute:i64,second:i64)->Time{
        Time::from_hour(hour)+Time::from_minute(minute)+Time::from_second(second)
    }

    pub fn get_second(&self)->i64{
        self.second
    }

    pub fn set_second(& mut self,second:i64){
        self.second=second;
    }

    pub fn get_minute(&self)->i64{
        self.second/60i64
    }

    pub fn set_minute(& mut self,minute:i64){
        self.second=self.second%60i64+minute*60i64;
    }

    pub fn get_hour(&self)->i64{
        self.second/3600i64
    }

    pub fn set_hour(& mut self,hour:i64){
        self.second=self.second%3600i64+hour*3600i64
    }

    pub fn get_day(&self)->i64{
        self.second/86400i64
    }

    pub fn set_day(& mut self, day:i64){
        self.second=self.second%86400i64+day*86400i64;
    }
}

//运算符重载 + - * /,实现加减及比例缩放。
impl Add<Time> for Time{//时间加法
    type Output = Self;
    fn add(self, other: Self) ->Time{
        Self{second:self.second + other.second}
    }
}

impl Sub<Time> for Time{//时间减法
    type Output = Self;
    fn sub(self, other: Self) ->Time{
        Self{second:self.second - other.second}
    }
}

impl Mul<i64> for Time{//时间比例缩放
    type Output = Self;
    fn mul(self, scale:i64) -> Time {
        Time::new(self.second * scale)
    }
}

impl Div<i64> for Time{//时间比例缩放
    type Output = Self;
    fn div(self, scale:i64) -> Time {
        Time::new(self.second / scale)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值