Getting timestamp from mongodb id

前端 未结 8 1737
误落风尘
误落风尘 2020-12-02 08:38

How do I get the timestamp from the MongoDB id?

相关标签:
8条回答
  • 2020-12-02 09:19

    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');
    }
    
    0 讨论(0)
  • 2020-12-02 09:22

    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

    0 讨论(0)
提交回复
热议问题