如何从时间

时间:2017-03-30 15:50:52

标签: c mongodb mongo-c-driver

在pymongo你可以做这样的事情来创建一个OID:

dummy_id = ObjectId.from_datetime(time)

在mongoc中有类似的东西吗?

我看到有一个“ bson_oid_get_time_t()”函数,但是它有一个反向函数,如果没有,它怎么能在C中实现?

1 个答案:

答案 0 :(得分:1)

我不相信有一个反向函数,但你应该很容易使用默认构造函数生成自己的函数并“修复”时间。

以下是我创建对象ID的示例。

然后我创建2014年12月25日的时间戳,并将OID修改为该日期。

#include <time.h>
#include <bson.h>

int
main (int   argc,
      char *argv[])
{
    time_t oid_thinks_time;  //what time does the OID think it is


    bson_oid_t oid;
    bson_oid_t *oid_pointer = &oid;
    bson_oid_init (&oid, NULL);  // get a standard ObjectId
    oid_thinks_time = bson_oid_get_time_t (&oid); //It was just made
    printf ("The OID was generated at %u\n", (unsigned) oid_thinks_time); //prove it



    time_t  ts = time(NULL);  //make a new time
    struct tm * timeinfo = localtime(&ts);
    timeinfo->tm_year = 2014-1900;  //-1900 because time.h
    timeinfo->tm_mon  = 12 - 1;     // time.h off by one (starts at 0)
    timeinfo->tm_mday = 25;
    ts = mktime(timeinfo);          // create the time
    u_int32_t ts_uint = (uint32_t)ts;
    ts_uint = BSON_UINT32_TO_BE (ts_uint); //BSON wants big endian time
    memcpy (&oid_pointer->bytes[0], &ts_uint, sizeof (ts_uint));  //overwrite the first 4 bytes with user selected time
    oid_thinks_time = bson_oid_get_time_t (&oid);
    printf ("The OID was fixed to time %u\n", (unsigned) oid_thinks_time);//prove it
}

此代码的输出为:

The OID was generated at 1491238015
The OID was fixed to time 1419526015