Tengo un time.Timevalor obtenido time.Now()y quiero obtener otro tiempo que es exactamente hace 1 mes.
Sé que es posible restar con time.Sub()(que quiere otro time.Time), pero eso resultará en un time.Durationy lo necesito al revés.
Tengo un time.Timevalor obtenido time.Now()y quiero obtener otro tiempo que es exactamente hace 1 mes.
Sé que es posible restar con time.Sub()(que quiere otro time.Time), pero eso resultará en un time.Durationy lo necesito al revés.
Respuestas:
Prueba AddDate :
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
then := now.AddDate(0, -1, 0)
fmt.Println("then:", then)
}
Produce:
now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC
Zona de juegos: http://play.golang.org/p/QChq02kisT
Subrestar tiempo. ¡Duh!
En respuesta al comentario de Thomas Browne, debido a que la respuesta de lnmx solo funciona para restar una fecha, aquí hay una modificación de su código que funciona para restar tiempo de un tipo de tiempo.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
count := 10
then := now.Add(time.Duration(-count) * time.Minute)
// if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
// then := now.Add(-10 * time.Minute)
fmt.Println("10 minutes ago:", then)
}
Produce:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Sin mencionar que también puede usar time.Houro en time.Secondlugar de time.Minutesegún sus necesidades.
Zona de juegos: https://play.golang.org/p/DzzH4SA3izp
ParseDurationutilices valores estáticos! Solo use -10 * time.Minute, para eso están definidas esas constantes. Por ejemplo, time.Now().Add(-10 * time.Minute)es todo lo que necesita.
now.Add(-10 * time.Minute)en now.Add(time.Duration(-10) * time.Minute)en caso de que obtenga un error al multiplicar una duración por un valor int ...
Puede negar un time.Duration:
then := now.Add(- dur)
Incluso puedes comparar a time.Durationcontra 0:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
Puede ver un ejemplo funcional en http://play.golang.org/p/ml7svlL4eW
-1 * durfuncionará, pero d := -1 ; dur = d * durgenerará un error: "tipos no coincidentes int y time.Duration"
Hay time.ParseDurationque aceptarán felizmente duraciones negativas, según el manual . Dicho de otra manera, no es necesario negar una duración en la que puede obtener una duración exacta en primer lugar.
Por ejemplo, cuando necesite restar una hora y media, puede hacerlo así:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
duration, _ := time.ParseDuration("-1.5h")
then := now.Add(duration)
fmt.Println("then:", then)
}