0

How can I convert a date earlier than 01-01-1970 to integer ? strtotime(); function waorks fine for dates later than 01-01-1970 but brings a negative value for dates like 05-07-1942

Thanks

2
Contributors
1
Reply
27
Views
3 Years
Discussion Span
Last Post by cereal
0

Hi,

It's normal because 0 equals to 01-01-1970 so, to get previous dates, you will receive negatives values. The problem is that, if you want to store it in MySQL, the from_unixtimestamp() function will not handle signed timestamps (i.e. negative values), if you want to display a datetime you will need a workaround. Example:

create table epoch (itime int(10) not null);
insert into epoch (itime) values(-unix_timestamp());
select * from epoch;

+-------------+
| itime       |
+-------------+
| -1391425879 |
+-------------+
1 row in set (0.00 sec)


SELECT DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), interval itime second),'%Y-%m-%d') as date from epoch;

+------------+
| date       |
+------------+
| 1925-11-28 |
+------------+
1 row in set (0.01 sec)

You get a similar result with the getdate() PHP function:

print_r(getdate(-1391425879));

Array
(
    [seconds] => 41
    [minutes] => 48
    [hours] => 13
    [mday] => 28
    [wday] => 6
    [mon] => 11
    [year] => 1925
    [yday] => 331
    [weekday] => Saturday
    [month] => November
    [0] => -1391425879
)

However, if you can, avoid unix timestamps and use datetime field types.

If you explain your goals we will try to suggest the best solution.

For more information check these links:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.