NAC_Blockchain/charter-std/utils/time.ch

99 lines
2.6 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Charter标准库 - 时间处理模块
// 提供时间戳、日期时间、时区转换等功能
module std::time;
// 时间戳结构
struct Timestamp {
seconds: u64, // Unix时间戳
nanos: u32, // 纳秒部分
}
impl Timestamp {
// 获取当前时间戳
public fun now() -> Timestamp {
let seconds = native_timestamp_seconds();
let nanos = native_timestamp_nanos();
Timestamp { seconds, nanos }
}
// 从秒创建时间戳
public fun from_seconds(seconds: u64) -> Timestamp {
Timestamp { seconds, nanos: 0 }
}
// 转换为秒
public fun as_seconds(&self) -> u64 {
self.seconds
}
// 转换为毫秒
public fun as_millis(&self) -> u64 {
self.seconds * 1000 + (self.nanos / 1_000_000) as u64
}
// 添加秒数
public fun add_seconds(&mut self, seconds: u64) {
self.seconds += seconds;
}
// 添加天数
public fun add_days(&mut self, days: u64) {
self.seconds += days * 86400;
}
// 比较时间戳
public fun is_before(&self, other: &Timestamp) -> bool {
if self.seconds < other.seconds {
return true;
}
if self.seconds == other.seconds && self.nanos < other.nanos {
return true;
}
false
}
// 计算时间差(秒)
public fun diff_seconds(&self, other: &Timestamp) -> u64 {
if self.seconds >= other.seconds {
self.seconds - other.seconds
} else {
other.seconds - self.seconds
}
}
}
// 日期时间结构
struct DateTime {
year: u32,
month: u8, // 1-12
day: u8, // 1-31
hour: u8, // 0-23
minute: u8, // 0-59
second: u8, // 0-59
}
impl DateTime {
// 创建日期时间
public fun new(year: u32, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> DateTime {
DateTime { year, month, day, hour, minute, second }
}
// 转换为时间戳
public fun to_timestamp(&self) -> Timestamp {
let seconds = datetime_to_unix(self.year, self.month, self.day, self.hour, self.minute, self.second);
Timestamp::from_seconds(seconds)
}
// 从时间戳创建
public fun from_timestamp(ts: &Timestamp) -> DateTime {
unix_to_datetime(ts.seconds)
}
}
// Native函数声明
native fun native_timestamp_seconds() -> u64;
native fun native_timestamp_nanos() -> u32;
native fun datetime_to_unix(year: u32, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> u64;
native fun unix_to_datetime(seconds: u64) -> DateTime;