C時(shí)間轉(zhuǎn)換為JSON含T(UTC)
#include <stdio.h> #include <time.h> #include <json-c/json.h> int main() { time_t t = time(NULL); struct tm *now = gmtime(&t); char buf[50]; strftime(buf, sizeof(buf),"%Y-%m-%dT%H:%M:%SZ", now); printf("UTC String: %s\n", buf); json_object *jobj = json_object_new_object(); json_object_object_add(jobj, "time", json_object_new_string(buf)); printf("JSON Object: %s\n", json_object_to_json_string(jobj)); return 0; }
本文通過C代碼演示了將當(dāng)前時(shí)間轉(zhuǎn)換為UTC時(shí)間格式并存儲為JSON對象的過程。代碼中首先調(diào)用time函數(shù)獲取當(dāng)前時(shí)間的時(shí)間戳,接著使用gmtime函數(shù)將時(shí)間戳轉(zhuǎn)換為UTC時(shí)區(qū)的時(shí)間結(jié)構(gòu)體。然后使用strftime函數(shù)將時(shí)間結(jié)構(gòu)體轉(zhuǎn)換為字符串格式,并按照ISO 8601標(biāo)準(zhǔn)的UTC時(shí)間格式存儲至buf數(shù)組中。最后,使用json-c庫的函數(shù)將時(shí)間字符串存儲至動態(tài)創(chuàng)建的JSON對象中,并打印輸出。