2015-10-21 35 views
-2

我有一個字符串10131520,我試圖轉換爲C中的Unix Epoch時間。如果數字分開像10-13-1520我可以使用類似strptime()的東西,但我有麻煩,因爲沒有刪除器。我正在考慮通過讀取前兩位並將它們存儲到一個月變量中,然後將後兩位存儲到一天中,然後最後四個時間存儲起來。如何將10131520轉換爲Unix時代的C時間?

如果任何人都可以指出我正確的方向,我將不勝感激。

感謝

+0

其字節,而不是位。只需使用其中一個字符串函數來提取您需要的值,並將其轉換爲您需要的形式。 – Marged

+1

您是否嘗試過「%m%d%Y」作爲格式?我不認爲strptime()需要分隔符。但它不會與1520年一起工作。字符串是否真的是MMDDYYYY格式,還是僅僅是嚴格挑選的例子? –

回答

0

這工作,有不同的方式,這是一個簡單,易於理解的方式。

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

    // to change 10131520 into 10-13-1520 


main() 
{ 
    char string[] = "10131520"; 
    char stringout[11]; 
    char year_str[5]; 
    char month_str[3]; 
    char day_str[3]; 

    month_str[0] = string[0]; 
    month_str[1] = string[1]; 
    month_str[2] = '\0'; 

    day_str[0] = string[2]; 
    day_str[1] = string[3]; 
    day_str[2] = '\0'; 

    year_str[0] = string[4]; 
    year_str[1] = string[5]; 
    year_str[2] = string[6]; 
    year_str[3] = string[7]; 
    year_str[4] = '\0'; 

    strcpy(stringout, month_str); 
    strcat(stringout, "-"); 
    strcat(stringout, day_str); 
    strcat(stringout, "-"); 
    strcat(stringout, year_str); 

    printf("\n the date is %s", stringout); 
    getchar(); 
} 
0

首先,獲取年,月,日你的字符串:

char my_date="10131520"; 
int my_date_n=atoi(my_date); // or any better method 

int month = (my_date_n/1000000)%100; 
int day = (my_date_n/ 10000)%100; 
int year = (my_date_n/  1)%10000; 

(有很多的這樣做的方法,這可能不是最好的。)

然後,通常用於遠日期,您會使用儒略日: https://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number

例如:

double calc_jd(int y, int mo, int d, 
       int h, int mi, float s) 
{ 
    // variant using ints 
    int A=(14-mo)/12; 
    int Y=y+4800-A; 
    int M=mo+12*A-3; 
    int JD=d + ((153*M+2)/5) + 365*Y + (Y/4) - (Y/100) + (Y/400) - 32045; 

    // add time of day at this stage 
    return JD + (h-12)/24.0 + mi/1440.0 + s*(1.0/86400.0); 
} 

然後你轉換這一個UNIX時間,這就是答案在這個問題上的逆:

Convert unix timestamp to julian

double unix_time_from_jd(double jd) 
{ 
    return (jd-2440587.5)*86400.0; 
} 

所以

double jd = calc_jd(year,month,day,12,0,0); // time of day, timezone? 
double unix_time = unix_time_from_jd(jd); 

注意,你可能會得到在 之間使用這種日期的普通工具,如果我們正在談論 1520年。(這就是爲什麼我在這裏繼續使用雙精度。)

相關問題