2014-10-27 62 views
0

一個子系統(我無法控制)將數據導出到mysql表中,並將日期存儲在從1900(http://support2.microsoft.com/kb/180162)開始的天數中。我需要將這些日期作爲unix時間戳記返回。使用mysql轉換日期,微軟1900日期系統

兩個日期

SELECT date FROM my_table WHERE id = 1 OR id = 2 
41315,3921180556 
41321,7267013889 

所需的輸出

SELECT some_magic(date) FROM my_table WHERE id = 1 OR id = 2 
1360488279 
1361035587 

我找不到,沒有工作的任何date-and-time-functions的例子。我錯過了什麼嗎?

我希望SELECT日期的輸出作爲我寫的PHP函數提供。

function UnMicrosoftify($fDateValue = 0, $iDateBase = 1900) { 
    if ($iDateBase == 1900) { 
     $iMyDateBase = 25569; 

     //Adjust for the fictional 29-Feb-1900 (Day 60) 
     if ($fDateValue < 60) { 
      --$iMyDateBase; 
     } 
    } else { 
     $iMyDateBase = 24107; 
    } 

    // Perform conversion 
    if ($fDateValue >= 1) { 
     $utcDays = $fDateValue - $iMyDateBase; 
     $iReturnValue = round($utcDays * 86400); 
     if (($iReturnValue <= PHP_INT_MAX) && ($iReturnValue >= -PHP_INT_MAX)) { 
      $iReturnValue = (integer) $iReturnValue; 
     } 
    } else { 
     $hours = round($fDateValue * 24); 
     $mins = round($fDateValue * 1440) - round($hours * 60); 
     $secs = round($fDateValue * 86400) - round($hours * 3600) - round($mins * 60); 
     $iReturnValue = (integer) gmmktime($hours, $mins, $secs); 
    } 
    return $iReturnValue; 
} 

echo UnMicrosoftify((float) str_replace(',','.', "41315,3921180556")) //displays 1360488279 (ie 2013-02-10 09:24:39) 
echo UnMicrosoftify((float) str_replace(',','.', "41321,7267013889")) //displays 1361035587 (ie 2013-02-16 17:26:27) 

是否有可能與MySQL做到這一點?怎麼樣?

回答

1

如果將日期存儲爲varchar,則必須將其轉換爲具有適當精度的小數點,然後按照第一個版本中的說明進行操作;如果它已經是第二個版本的小數點。

試試這個,我認爲這是你想要什麼:

SELECT 
    date AS ExcelSerialDate, 

    ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00', 
          cast(replace(date,',','.') as DECIMAL(30,12))), 
       INTERVAL -1 DAY), INTERVAL (MOD(date,1) * 86400) SECOND) 
    AS ConvDate, 

    UNIX_TIMESTAMP(
    ADDDATE(
     ADDDATE(
     ADDDATE('1899-12-31 00:00', 
       cast(replace(date,',','.') as DECIMAL(30,12))), 
     INTERVAL -1 DAY), 
     INTERVAL (
     MOD(cast(replace(date,',','.') as DECIMAL(30,12)),1) * 86400 
    ) SECOND 
    ) 
) 
    AS UnixTS_From_varchar, 

    UNIX_TIMESTAMP(
    ADDDATE(
     ADDDATE(
     ADDDATE('1899-12-31 00:00',date2), 
     INTERVAL -1 DAY), 
     INTERVAL (
     MOD(date2,1) * 86400 
    ) SECOND 
    ) 
) 
    AS UnixTS_from_double  

FROM my_table; 

Sample SQL Fiddle

與樣品數據這給:

EXCELSERIALDATE  CONVDATE    UNIXTS_FROM_VARCHAR UNIXTS_FROM_DOUBLE 
41315,3921180556 2013-02-10 00:00:00 1360488279   1360488279 
41321,7267013889 2013-02-17 00:00:00 1361121987   1361121987 
+0

看來真的是有前途的,除了它下降的部分時間.. – daker 2014-10-27 14:28:53

+1

太棒了!十分感謝 :) – daker 2014-10-27 15:02:19