What does 20060102150405 mean? - go

I would like to get current time value. I found this answer which works for me but don't know why format method take 20060102150405 value? Not like yyyyMMdd hhmmss.

Go's time formatting unique and different than what you would do in other languages. Instead of having a conventional format to print the date, Go uses the reference date 20060102150405 which seems meaningless but actually has a reason, as it's 1 2 3 4 5 6 in the Posix date command:
Mon Jan 2 15:04:05 -0700 MST 2006
0 1 2 3 4 5 6
The timezone is 7 but that sits in the middle, so in the end the format resembles 1 2 3 4 5 7 6.
This online converter is handy, if you are transitioning from the strftime format.
Interesting historical reference: https://github.com/golang/go/issues/444
The time package provides handy constants as well:
const (
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
)
You can use them like this:
t := time.Now()
fmt.Println(t.Format(time.ANSIC))

See https://golang.org/pkg/time/#pkg-constants It is the time "01/02 03:04:05PM '06 -0700" Because each component has a different number (1, 2, 3, etc.), it can determine from the numbers what components you want.

20060102150405 is a date and time format 2006/01/02 15:04:05
package main
import (
"fmt"
"time"
)
func main() {
date1 := time.Now().Format("2006/01/02 15:04")
fmt.Println(date1)//2009/11/10 23:00
date2 := time.Now().Format("20060102150405")
fmt.Println(date2)//20091110230000
}
https://play.golang.org/p/kIfNRQ50JP

Related

golang convert date string(Oct 10 2022) into date format [duplicate]

This question already has answers here:
How to format current time using a yyyyMMddHHmmss format?
(6 answers)
Parsing date/time strings which are not 'standard' formats
(4 answers)
Closed 4 months ago.
I have a date string Oct 10 2022 and I want to convert this to a time object. I have tried with time.Parse, but it always returns 0001-01-01 00:00:00 +0000 UTC
date := "Oct 10 2022"
output, _ := time.Parse(time.ANSIC, date)
fmt.Println(output)
How do I get a time object from the above string?
for cast your favorite time string to time.ANSIC, you must do it like below
date = "Mon Oct 10 15:04:05 2022"
output, _ := time.Parse(time.ANSIC, date)
fmt.Println(output)
other time package constants for cast like below:
Layout = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
ANSIC = "Mon Jan 2 15:04:05 2006"
UnixDate = "Mon Jan 2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
Stamp = "Jan 2 15:04:05"
StampMilli = "Jan 2 15:04:05.000"
StampMicro = "Jan 2 15:04:05.000000"
StampNano = "Jan 2 15:04:05.000000000"

How to convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO

How do i convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO?
For example:
var milleSecond int64
milleSecond = 1645286399999 //My Local Time : Sat Feb 19 2022 23:59:59
var loc = time.FixedZone("UTC-4", -4*3600)
string1 := time.UnixMilli(end).In(loc).Format(time.RFC3339)
Actual Result: 2022-02-19T11:59:59-04:00
Expected Result(should be): 2022-02-19T11:59:59.999-04:00
You are asking for an RFC3339 formatted string, with seconds reported to the nearest millisecond. There's no format string in the time package for this (only with whole seconds and nanosecond accuracy), but you can make your own.
Here's the string for seconds to the nearest nanosecond, copied from the standard library:
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
You can make a millisecond version of this easily enough by removing the .999999999 (report time to the nearest nanosecond, removing trailing zeros) to .000 (report time to the nearest millisecond, don't remove trailing zeros). This format is documented under time.Layout in the package docs https://pkg.go.dev/time#pkg-constants:
RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
Code (playground link):
package main
import (
"fmt"
"time"
)
const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
func main() {
ms := int64(1645286399999) //My Local Time : Sat Feb 19 2022 23:59:59
var loc = time.FixedZone("UTC-4", -4*3600)
fmt.Println(time.UnixMilli(ms).In(loc).Format(RFC3339Milli))
}
Output:
2022-02-19T11:59:59.999-04:00

Why does golang time function fail on certain dates [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have checked the other suggestions for fixing this problem and they don't work.
The current code seems to work until you enter a different date and then I get random failures like below.
The code is as follows:
yy, mm, dd = 11, 27, 2019
s_yy, s_mm, s_dd = 11, 1, 2019
e_yy, e_mm, e_dd = 1, 1, 2020
input := fmt.Sprintf("%d-%d-%d", yy, mm, dd)
input += "T15:04:05.000-07:00"
t, _ := time.Parse("2006-01-02T15:04:05.000-07:00", input)
input_s := fmt.Sprintf("%d-%d-%d", s_yy, s_mm, s_dd)
input_s += "T15:04:05.000-07:00"
t_s, _ := time.Parse("2006-01-02T15:04:05.000-07:00", input_s)
input_e := fmt.Sprintf("%d-%d-%d", e_yy, e_mm, e_dd)
input_e += "T15:04:05.000-07:00"
t_e, _ := time.Parse("2006-01-02T15:04:05.000-07:00", input_e)
fmt.Println("t = ", t, " t_s = ", t_s, " t_e", t_e)
The result is the following:
t = 2019-12-27 15:04:05 -0700 -0700 t_s = 0001-01-01 00:00:00 +0000 UTC t_e 0001-01-01 00:00:00 +0000 UTC
Any Help would be a help
Thanks in advance.
You got problems in your code.
The order of your variable is wrong.
yy, mm, dd = 11, 27, 2019 should be yy, mm, dd = 2019, 11, 27.
Don't ignore the error. If you got problem, just print it will be a lot of help (or better is writing a test)
Your format is wrong. It should in form like fmt.Sprintf("%d-%02d-%02d", yy, mm, dd)
You can check the result here

Duplicate Keys noticed while writing to TOML file; tree.Has() is not working as expected

While writing into TOML file using go-toml parser, I'm seeing all duplicate entries.
Which one is correct about tree.WriteTo() function?
a. overwrites the fields in the file
b. appends the tree to the file? i.e., to the existing file, write the tree content again.
I wanted to achieve the update operation to the existing config parameter (present in TOML file).
I tried this:
//Read the config file
tree, _ := toml.LoadFile("/home/robot/test.toml")
//Read user input
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
//Check whether the input config parameter is present in the file or not
configArray := strings.Split(string(reqBody), ";")
for index, each := range configArray {
config := strings.Split(each, "=")
fmt.Println("Param name : ", config[0])
fmt.Println("Param value : ", config[1])
fmt.Println(index)
isPresent := tree.Has(config[0])
fmt.Println(isPresent)
if isPresent == true {
tree.Set(config[0], config[1])
}else {
fmt.Println("Config Parameter not found")
}
}
// Now the tree has updated values, update the file.
outputReader, err = os.OpenFile("/home/robot/test.toml",os.O_RDWR,0644)
if err != nil {
fmt.Println("Error opening the file")
}
var numBytes int64
numBytes, err = tree.WriteTo(outputReader)
if err != nil {
fmt.Println("Error writing to the file")
}
fmt.Println(numBytes)
tree.Has() is always returning false, even though the valid key is provided. Not sure why! Please see the output logs pasted.
tree.WriteTo() is appending all the tree entries to the file. i.e., it is not updating the parameter values, but writing everything newly resulting in duplicate configuration parameters in the file.
If tree.WriteTo() is meant to write entire tree content to file, then is there any API or way to update the existing configurations in TOML file?
Output logs:
TOML content (i.e., dump of tree):
Sep 03 13:27:33 mn-0 janus[31157]: [http]
Sep 03 13:27:33 mn-0 janus[31157]: enableAudit = true
Sep 03 13:27:33 mn-0 janus[31157]: idleTimeout = "600s"
Sep 03 13:27:33 mn-0 janus[31157]: logLevel = "debug"
Sep 03 13:27:33 mn-0 janus[31157]: port = 443
Sep 03 13:27:33 mn-0 janus[31157]: readTimeout = "10s"
Sep 03 13:27:33 mn-0 janus[31157]: tlsMode = true
Sep 03 13:27:33 mn-0 janus[31157]: writeTimeout = "10s"
Sep 03 13:27:33 mn-0 janus[31157]: [http.cred]
Sep 03 13:27:33 mn-0 janus[31157]: sessionValidity = "1h"
Sep 03 13:27:33 mn-0 janus[31157]: strictSecureMode = false
Sep 03 13:27:33 mn-0 janus[31157]: users = ["robot"]
Sep 03 13:27:33 mn-0 janus[31157]: [http.ipConfig]
Sep 03 13:27:33 mn-0 janus[31157]: ipAddr = ""
Sep 03 13:27:33 mn-0 janus[31157]: role = "ssh"
Input invalid key:
Sep 03 13:27:33 mn-0 janus[31157]: Param name : http.enableAudt
Sep 03 13:27:33 mn-0 janus[31157]: Param value : true
Sep 03 13:27:33 mn-0 janus[31157]: 0
Sep 03 13:27:33 mn-0 janus[31157]: false
Input valid Key:
Sep 03 13:27:33 mn-0 janus[31157]: Param name : http.enableAudit
Sep 03 13:27:33 mn-0 janus[31157]: Param value : false
Sep 03 13:27:33 mn-0 janus[31157]: 1
Sep 03 13:27:33 mn-0 janus[31157]: false
One more question on unmarshal() or configuration validation while reading,
Say my structure is like this.
type IPConfig struct {
User string
Role string
IPAddr string
}
type MyConfiguration struct {
MyConfiguration MyConfiguration
}
a.
If the TOML file has this:
[ipConfig]
role = "ssh"
ipAddr = ""
i.e., it doesn't have one more parameter, "User". How do I catch this while Unmarshal? At least Unmarshal() will not throw any error here.
b.
If the TOML file has this:
[ipConfig]
role = "ssh"
ipAddr = ""
user = "lauren"
abc = "xyz"
i.e., it has extra configuration parameter "abc". How to catch this? Unmarshal() didn't throw any error even for this.
Any way to get these validation errors?
For question 1:
It is hard to figure out what may be going on without having access to the content of the files. If you believe this is a bug, please open an issue on Github, including the reproduction steps. Thank you!
For question 2:
You need to remove or truncate the file before writing to it.
Go-toml does not know that you are writing to a file. WriteTo takes a io.Writer, which just signifies "something you can write to". So when you open the file for read/write, the "writer" part of the file has a 0 offset. So when toml writes to it (using WriteTo), it will just be replacing bytes to the file.
If you want to overwrite the content of the file using WriteTo, you need to call .truncate(0) or similar on the file before writing to it.
Note: as of writing, comments are discarded during Load. There is an issue on Github asking for that feature.
For question 3:
There is no support for erroring on missing keys or on extra keys. There is an issue open at the moment to support the latter.

javascript validate date in the past

I want to compare if a given date is in the past or future.
The given date is coming in from a string in yyyy-mm-dd format.
I tried to "even out" the today and compensating the timezone in the given date date but I am sure there must be a better way to this??
var today = new Date();
console.log("TODAY: " + today); // Mon Apr 28 2014 14:46:41 GMT+0200 (CEST)
var todayYear = today.getFullYear();
var todayMonth = today.getMonth();
todayMonth = parseInt(todayMonth, 10) + 1;
var todayDay = today.getDate();
var todayFormatted = todayYear + "-" + todayMonth + "-" + todayDay;
today = new Date(todayFormatted);
console.log("TODAY: " + today); // Mon Apr 28 2014 00:00:00 GMT+0200 (CEST)
var testDate = new Date("2014-04-28");
console.log("TEST: " + testDate); // Mon Apr 28 2014 02:00:00 GMT+0200 (CEST)
testDate.setHours(00);
console.log("TEST: " + testDate);
// check if test is in the past
(testDate < today) ? console.log('test is in the past') : console.log('test is NOT in the past');
You can compare the "Unix times" mathematically:
var today = new Date();
console.log(testDate.getTime() < today.getTime()
? 'test is in the past'
: 'test is NOT in the past');

Resources