Skip to content

日期转换 #14

@kevinyan815

Description

@kevinyan815

把时间格式字符串解析成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
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions