github.com/decred/politeia@v1.4.0/politeiawww/cmd/pictl/time.go (about) 1 // Copyright (c) 2020-2021 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "time" 9 ) 10 11 const ( 12 // dateAndTimeFormat contains the reference time format that is used 13 // to print a human readable date and time. 14 // 15 // Reference date: "Mon Jan 2 15:04:05 2006" 16 dateAndTimeFormat = "2 Jan 2006 3:04:05pm" 17 18 // userInputDateFormat contains the reference time format that is used to 19 // parse user input dates. 20 // 21 // Reference date: "Mon Jan 2 15:04:05 2006" 22 userInputDateFormat = "01/02/2006" 23 24 // locationName is the name of the time zone location that is used 25 // in the human readable timestamps. 26 locationName = "Local" 27 ) 28 29 // dateAndTimeFromUnix converts a unix timestamp into a human readable 30 // timestamp string formatted according to the dateAndTime global variable. 31 func dateAndTimeFromUnix(unixTime int64) string { 32 t := time.Unix(unixTime, 0) 33 return t.Format(dateAndTimeFormat) 34 } 35 36 // dateFromUnix coverts a unix timestamp into a human readable timestamp string 37 // formatted according to the userInputDateFormat global variable. 38 func dateFromUnix(unixTime int64) string { 39 t := time.Unix(unixTime, 0) 40 return t.Format(userInputDateFormat) 41 } 42 43 // unixFromDate converts a human readable timestamp string formatted according 44 // to the userInputDateFormat global variable into a unix timestamp. 45 func unixFromDate(timestamp string) (int64, error) { 46 location, err := time.LoadLocation(locationName) 47 if err != nil { 48 return 0, err 49 } 50 t, err := time.ParseInLocation(userInputDateFormat, timestamp, location) 51 if err != nil { 52 return 0, err 53 } 54 55 return t.Unix(), nil 56 }