How do I get the timestamp from the MongoDB id?
Here is a quick php function for you all ;)
public static function makeDate($mongoId) {
$timestamp = intval(substr($mongoId, 0, 8), 16);
$datum = (new DateTime())->setTimestamp($timestamp);
return $datum->format('d/m/Y');
}
If you need to get timestamp from MongoID in a GoLang:
package main
import (
"fmt"
"github.com/pkg/errors"
"strconv"
)
const (
mongoIDLength = 24
)
var ErrInvalidMongoID = errors.New("invalid mongoID provided")
func main() {
s, err := ExtractTimestampFromMongoID("5eea13924a04cb4b58fe31e3")
if err != nil {
fmt.Print(err)
return
}
fmt.Printf("%T, %v\n", s, s)
// convert to usual int
usualInt := int(s)
fmt.Printf("%T, %v\n", usualInt, usualInt)
}
func ExtractTimestampFromMongoID(mongoID string) (int64, error) {
if len(mongoID) != mongoIDLength {
return 0, errors.WithStack(ErrInvalidMongoID)
}
s, err := strconv.ParseInt(mongoID[0:8], 16, 0)
if err != nil {
return 0, err
}
return s, nil
}
Playground: https://play.golang.org/p/lB9xSCmsP8I