Hora de Go / golang.Ahora().UnixNano() convertir a milisegundos?


¿Cómo puedo obtener tiempo Unix en Go en milisegundos?

Tengo la siguiente función:

func makeTimestamp() int64 {
    return time.Now().UnixNano() % 1e6 / 1e3
}

Necesito menos precisión y solo quiero milisegundos.

Author: mconlin, 2014-06-09

4 answers

Simplemente divídelo:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

Aquí hay un ejemplo que puede compilar y ejecutar para ver la salida

package main

import (
    "time"
    "fmt"
)

func main() {
    a := makeTimestamp()

    fmt.Printf("%d \n", a)
}

func makeTimestamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}
 67
Author: OneOfOne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 12:18:19

Como @Jono señala en la respuesta de @OneOfOne, la respuesta correcta debe tener en cuenta la duración de un nanosegundo. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

La respuesta de OneOfOne funciona porque time.Nanosecond pasa a ser 1, y dividir por 1 no tiene efecto. No se lo suficiente acerca de go para saber qué tan probable es que esto cambie en el futuro, pero para la respuesta estrictamente correcta usaría esta función, no la respuesta de OneOfOne. Dudo que haya alguna desventaja de rendimiento ya que el compilador debería ser capaz de optimizar esto perfectamente bien.

Véase https://en.wikipedia.org/wiki/Dimensional_analysis

Otra forma de ver esto es que tanto time.Now().UnixNano() como time.Millisecond usan las mismas unidades (nanosegundos). Mientras eso sea cierto, la respuesta de OneOfOne debería funcionar perfectamente bien.

 37
Author: Bjorn Roche,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-02 17:16:08

Mantenlo simple.

func NowAsUnixMilli() int64 {
    return time.Now().UnixNano() / 1e6
}
 6
Author: stratovarius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 08:23:00

Creo que es mejor redondear el tiempo a milisegundos antes de la división.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Aquí hay un programa de ejemplo:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

El programa anterior imprimió el siguiente resultado en mi máquina:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST
 -1
Author: hnakamur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-27 16:10:15