Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UNIX time before 1970 to date format in MySQL?

I have a database using unix time for its dates ( i am using mySQL). I want to retrieve the dates in daily date format. This is my query:

SELECT FROM_UNIXTIME(time_created) FROM member

This works fine with dates after 1970 (for example, 1314162229) but doesn't work for dates before 1970 (for example, -769338000). Is there any work around here?

like image 577
why.you.and.i Avatar asked Aug 24 '11 05:08

why.you.and.i


People also ask

How can get date in dd mm yyyy format in MySQL?

The following is the query to format the date to YYYY-MM-DD. mysql> select str_to_date(LoginDate,'%d. %m.

Why does 1970 timestamp start?

January 1st, 1970 at 00:00:00 UTC is referred to as the Unix epoch. Early Unix engineers picked that date arbitrarily because they needed to set a uniform date for the start of time, and New Year's Day, 1970, seemed most convenient.

Can we change date format in MySQL?

Change the curdate() (current date) format in MySQL The current date format is 'YYYY-mm-dd'. To change current date format, you can use date_format().


1 Answers

A possible workaround would be to have a constant handy corresponding to the seconds in a certain number of years (preferrably a multiple of 4). You could add this constant, translate the time and then subtract the number of years chosen.

Example: choose 40 years.

Determine the constant:

MySQL [files]> select adddate(from_unixtime(0), interval 40 year);
+---------------------------------------------+
| adddate(from_unixtime(0), interval 40 year) |
+---------------------------------------------+
| 2010-01-01 01:00:00                         |
+---------------------------------------------+
1 row in set (0.09 sec)

MySQL [files]> select unix_timestamp(adddate(from_unixtime(0), interval 40 year));
+-------------------------------------------------------------+
| unix_timestamp(adddate(from_unixtime(0), interval 40 year)) |
+-------------------------------------------------------------+
|                                                  1262304000 |
+-------------------------------------------------------------+
1 row in set (0.09 sec)

Now you can every unix timestamp x between 1930 and 20xx and use it.

select subdate(from_unixtime(x+1262304000), interval 40 year);

With your example -769338000, you get

MySQL [files]> select subdate(from_unixtime(-769338000+1262304000), interval 40 year);
+-----------------------------------------------------------------+
| subdate(from_unixtime(-769338000+1262304000), interval 40 year) |
+-----------------------------------------------------------------+
| 1945-08-15 17:00:00                                             |
+-----------------------------------------------------------------+
1 row in set (0.09 sec)
like image 124
glglgl Avatar answered Oct 21 '22 00:10

glglgl