使用mysql,Microsoft 1900 Date系统转换日期

时间:2014-10-27 14:09:15

标签: mysql sql date

子系统(我无法控制)将数据导出到mysql表,并以1900(http://support2.microsoft.com/kb/180162)的天数存储日期。我需要将这些日期作为unix时间戳返回。

两个日期的例子

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 个答案:

答案 0 :(得分: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