Formattare Data Su Go
Ipotizziamo di avere il seguente codice:
t := time.Now()
fmt.Println(t.Format("yyyyMMddHHmmss"))
Come possiamo formattare la data nel formato: yyyyMMddHHmmss? La domanda è molto semplice e la risposta è quasi banale. Tuttavia il motivo di questa risposta cela uno dei grandi incubi dei programmatori che scrivono con GoLang.
2 Gennaio 2006
Per formattare la data è sufficiente inserire fmt.Println(t.Format("20060102150405"))
. Mh, sembra molto strano a prima vista. Perché includiamo una data? E perchè proprio il 2 Gennaio 2006?
Si scopre in realtà che dietro questa assurda data scelta a tavolino, c’è una scelta ingegneristica molto acuta. La funzione “Parse” che serve per analizzare una stringa non utilizza alcuna regola per il parsing, ma si basa sul “query-by-example”. Il query-by-example è una tecnica che permette di parsare una stringa in base ad una query di esempio che viene confrontata con la stringa parsata.
È stata scelta proprio tale data per la rappresentazione timestamp della data; infatti se prendessimo la data (Mon Jan 2 15:04:05 -0700 MST 2006 ), scopriremo che:
- mese: gennaio (valore: 1)
- giorno: 2
- ora: 15 (ovvero 3 nella rappresentazione a.m./p.m.)
- minuti: 4
- secondi: 5
- anno: 6
- timezone: 7
Il codice di Go menziona infatti il “query-by-example”:
// The layout string used by the Parse function and Format method
// shows by example how the reference time should be represented.
// We stress that one must show how the reference time is formatted,
// not a time of the user's choosing. Thus each layout string is a
// representation of the time stamp,
// Jan 2 15:04:05 2006 MST
// An easy way to remember this value is that it holds, when presented
// in this order, the values (lined up with the elements above):
// 1 2 3 4 5 6 -7
Alcuni dettagli e una discussione storica possono essere trovati su Github.