簡體   English   中英

如何將字符串(以微秒為單位)轉換為C中的struct tm?

[英]How to convert character string in microseconds to struct tm in C?

我有一個字符串,包含自紀元以來的微秒。 我怎么能把它轉換成時間結構?

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    struct tm tm; 
    char buffer [80];
    char *str ="1435687921000000";
    if(strptime (str, "%s", &tm) == NULL)
        exit(EXIT_FAILURE); 
    if(strftime (buffer,80,"%Y-%m-%d",&tm) == 0)
        exit(EXIT_FAILURE);

    printf("%s\n", buffer);

    return 0;
}

便攜式解決方案(假設32位int )。 以下不假設有關time_t任何內容。

使用mktime() ,不需要將字段限制在其主要范圍內。

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  char buffer[80];
  char *str = "1435687921000000";

  // Set the epoch: assume Jan 1, 0:00:00 UTC.
  struct tm tm = { 0 };
  tm.tm_year = 1970 - 1900;
  tm.tm_mday = 1;

  // Adjust the second's field.
  tm.tm_sec = atoll(str) / 1000000;
  tm.tm_isdst = -1;
  if (mktime(&tm) == -1)
    exit(EXIT_FAILURE);
  if (strftime(buffer, 80, "%Y-%m-%d", &tm) == 0)
    exit(EXIT_FAILURE);
  printf("%s\n", buffer);
  return 0;
}

編輯:您可以簡單地截斷字符串,因為struct tm精度不會低於1秒。

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
    struct tm now; 
    time_t secs;
    char buffer [80];
    char str[] ="1435687921000000";
    int len = strlen(str);
    if (len < 7)
        return 1;
    str[len-6] = 0;                     // divide by 1000000
    secs = (time_t)atol(str);
    now = *localtime(&secs);

    strftime(buffer, 80, "%Y-%m-%d", &now);
    printf("%s\n", buffer);

    printf("%s\n", asctime(&now));
    return 0;
}

節目輸出:

2015-06-30
Tue Jun 30 19:12:01 2015

您可以將微秒轉換為秒,並像這樣使用localtime()

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main (void)
{
    struct tm *tm; 
    char   buffer[80];
    char  *str = "1435687921000000";
    time_t ms  = strtol(str, NULL, 10);

    /* convert to seconds */
    ms = (time_t) ms / 1E6;
    tm = localtime(&ms);
    if (strftime(buffer, 80, "%Y-%m-%d", tm) == 0)
        return EXIT_FAILURE;

    printf("%s\n", buffer);

    return EXIT_SUCCESS;
}

請注意,在打印日期中,微秒不存在,因此您可以忽略該部分。

將字符串轉換為time_t,然后使用gmtime(3)或localtime(3)。

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main () {
        struct tm *tm;
        char buffer [80];
        char *str ="1435687921000000";
        time_t t;

        /* or strtoull */
        t = (time_t)(atoll(str)/1000000);

        tm = gmtime(&t);

        strftime(buffer,80,"%Y-%m-%d",tm);

        printf("%s\n", buffer);

        return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM