Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

日期转换 #14

Open
kevinyan815 opened this issue Dec 12, 2019 · 0 comments
Open

日期转换 #14

kevinyan815 opened this issue Dec 12, 2019 · 0 comments

Comments

@kevinyan815
Copy link
Owner

kevinyan815 commented Dec 12, 2019

把时间格式字符串解析成Time对象

package main

import (
	"fmt"
	"time"
)

const TimeLayoutDefault = "2006-01-02 15:04:05"
const TimeLayoutDate = "20060102"
const TimeLayoutBirthday = "2006-01-02"

func main() {
    DateString := "2019-12-12"
    fullTimeString := "2020-09-18 13:45:22"
    shortTimeString := "19930606"

    utcDate, _ := time.Parse(TimeLayoutBirthday, DateString)// omit returned err in example
    localDate, _ := time.ParseInLocation(TimeLayoutBirthday, DateString, time.Local)// time.Local represents the system's local time zone.

    time1, _ := time.ParseInLocation(TimeLayoutDefault, fullTimeString, time.Local)
    time2, _ := time.ParseInLocation(TimeLayoutDate, shortTimeString, time.Local)

    fmt.Println(utcDate, localDate, time1, time2)
}

Time对象格式化成字符串

const TimeLayoutDefault = "2006-01-02 15:04:05"
const TimeLayoutNumeric = "20060102"

// 当前时间的字符串表示
time.Now().Format(TimeLayoutDefault)
time.Now().Format(TimeLayoutNumeric)

Time 对象和时间戳的互换

stamp := time.Now().Unix() // 当前时间对应的时间戳

time.Unix(stamp, 0) // 时间戳对应的Time对象

获取时间对象的年、月、日

使用 Time 对象的 Date 方法获取时间对象的年、月、日

func (t Time) Date() (year int, month Month, day int)
year, month, day := time.Now().Date()
fmt.Println(year, month, day)      // For example 2009 November 10
fmt.Println(year, int(month), day) // For example 2009 11 10

也可以像下面这样调用单独的函数获取年、月、日

t := time.Now()
year := t.Year()   // type int
month := t.Month() // type time.Month
day := t.Day()     // type int

A Month specifies a month of the year (January = 1, ...).

type Month int
const (
    January Month = 1 + iota
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
)
@kevinyan815 kevinyan815 changed the title 日期函数 日期转换 Dec 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant