3

GO 获取时间的年份、月份以及日期

 3 years ago
source link: https://studygolang.com/articles/5085?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

GO 获取时间的年份、月份以及日期

dengpei187 · 2015-10-24 21:00:06 · 30813 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2015-10-24 21:00:06 的文章,其中的信息可能已经有所发展或是发生改变。

网上很多资料提供time将时间戳转成字符串的例子,但如何将获得的时间分为年、月、日分别展示,例如:
这里写图片描述,上面显示的是日期,下面显示的是月份。作为初学者,表示网上的资料有点看不懂,记录一下,还望斧正。

首先要获取一个Time类型的变量,平时要获取现在的时间的话,直接使用now即可,但若是从数据库中读取的数据应当如何呢?下面叙述:

直接获取系统时间

year:=time.Now().Year()
month:=time.Now().Month()//time.Now().Month().String()
day:=time.Now().Day()

引用数据库中时间数据

month = time.Unix(dynamic.UpdateTime/1000, 0).Month().String()
day = time.Unix(dynamic.UpdateTime/1000, 0).Day()
year = time.Unix(dynamic.UpdateTime/1000, 0).Year()

其中dynamic.UpdateTime为从数据库中读取出来的时间字段,先转为Time类型,再去获取月份、日期等。

当然也可以在其结构体中加几个字段(不带json),方便前端的显示。需要注意的是,year和day均为int类型,而month为string类型。

其实这个还是比较简单的,只不过作为初学者不太了解,希望有帮助。

版权声明:本文为博主原创文章,未经博主允许不得转载。


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK