Go 日期时间包装器:15条更便捷的时间处理

warning: 这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。



package main
 
import (
    "fmt"
    "time"
)
 
// 定义一个包装time.Time的结构体
type MyTime struct {
    time.Time
}
 
// 实现AddDate方法,添加年、月、日
func (mt *MyTime) AddDate(years int, months int, days int) MyTime {
    return MyTime{mt.Time.AddDate(years, months, days)}
}
 
// 实现AddDuration方法,添加时间段
func (mt *MyTime) AddDuration(d time.Duration) MyTime {
    return MyTime{mt.Time.Add(d)}
}
 
// 实现Format方法,格式化时间
func (mt *MyTime) Format(layout string) string {
    return mt.Time.Format(layout)
}
 
// 实现IsBefore方法,判断是否在另一个时间之前
func (mt *MyTime) IsBefore(other MyTime) bool {
    return mt.Time.Before(other.Time)
}
 
// 实现IsAfter方法,判断是否在另一个时间之后
func (mt *MyTime) IsAfter(other MyTime) bool {
    return mt.Time.After(other.Time)
}
 
func main() {
    now := MyTime{time.Now()}
    fmt.Println("当前时间:", now.Format("2006-01-02 15:04:05"))
 
    tomorrow := now.AddDate(0, 0, 1)
    fmt.Println("明天时间:", tomorrow.Format("2006-01-02"))
 
    nextWeek := now.AddDuration(7 * 24 * time.Hour)
    fmt.Println("下周时间:", nextWeek.Format("2006-01-02"))
 
    fmt.Println("现在是否在明天之前:", now.IsBefore(tomorrow))
    fmt.Println("下周是否在现在之后:", nextWeek.IsAfter(now))
}

这段代码首先定义了一个结构体MyTime来包装time.Time,然后为这个结构体实现了一系列方法来简化时间的操作和检查。它展示了如何添加年、月、日(AddDate)、添加特定的时间段(AddDuration)、格式化时间(Format)以及比较时间(IsBeforeIsAfter)。这些方法使得时间的处理更加直观和方便。

最后修改于:2024年08月11日 10:12

评论已关闭

推荐阅读

DDPG 模型解析,附Pytorch完整代码
2024年11月24日
DQN 模型解析,附Pytorch完整代码
2024年11月24日
AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日