Converting a date string which is before 1970 into a timestamp in MySQL

后端 未结 8 1688
名媛妹妹
名媛妹妹 2020-12-17 14:51

Not a very good title, so my apologies.

For some reason, (I wasn\'t the person who did it, i digress) we have a table structure where the field type for a date is va

相关标签:
8条回答
  • 2020-12-17 15:07

    convert these date strings into a unix time stamp

    Traditional Unix timestamps are an unsigned integer count of seconds since 1-Jan-1970 therefore can't represent any date before that.

    0 讨论(0)
  • 2020-12-17 15:07

    To get the max. Range +/- wise use this query on your birthday field, in my case "yyyy-mm-dd" but you can change it to your needs

    select name, (@bday:=STR_TO_DATE(birthday,"%Y-%m-%d")),if(year(@bday)<1970,UNIX_TIMESTAMP(affffdate(@bday, interval 68 year))-2145916800,UNIX_TIMESTAMP(@bday)) from people
    
    0 讨论(0)
  • 2020-12-17 15:07

    Use Date instead of timestamps. Date will solve your Problems. check this link

    0 讨论(0)
  • 2020-12-17 15:10

    I've adapted the DATEDIFF workaround to also include time not just days. I've wrapped it up into a stored function, but you can just extract the SELECT part out if you don't want to use functions.

    DELIMITER |
    CREATE FUNCTION SIGNED_UNIX_TIMESTAMP (d DATETIME)
    RETURNS BIGINT
     DETERMINISTIC
      BEGIN
        DECLARE tz VARCHAR(100);
        DECLARE ts BIGINT;
        SET tz = @@time_zone;
        SET time_zone = '+00:00';
        SELECT DATEDIFF(d, FROM_UNIXTIME(0)) * 86400 +
        TIME_TO_SEC(
          TIMEDIFF(
            d,
            DATE_ADD(MAKEDATE(YEAR(d), DAYOFYEAR(d)), INTERVAL 0 HOUR)
          )
        ) INTO ts;
        SET time_zone = tz;
        return ts;
      END|
    DELIMITER ;
    
    -- SELECT UNIX_TIMESTAMP('1900-01-02 03:45:00');
    -- will return 0
    -- SELECT SIGNED_UNIX_TIMESTAMP('1900-01-02 03:45:00');
    -- will return -2208888900
    
    0 讨论(0)
  • 2020-12-17 15:10

    If its feasible for your problem, you could shift all your mysql times by, say 100 years, and then work with those adjusted timestamps or re calculate the negative timestamp value.

    As some have said, make sure your system is using 64bits to represent the timestamp otherwise you'll hit the year 2038 problem.

    0 讨论(0)
  • 2020-12-17 15:17

    Aha! We've found a solution!

    The SQL to do it:

    SELECT DATEDIFF( STR_TO_DATE('04-07-1988','%d-%m-%Y'),FROM_UNIXTIME(0))*24*3600 -> 583977600
    SELECT DATEDIFF( STR_TO_DATE('04-07-1968','%d-%m-%Y'),FROM_UNIXTIME(0))*24*3600 -> -47174400 
    

    This could be useful for future reference.

    You can test it here: http://www.onlineconversion.com/unix_time.htm

    0 讨论(0)
提交回复
热议问题