Convert Unix dates for export to Excel with PHP

phplogoIts easy enough to export formatted dates as strings to a .csv file for Excel, but if you want to be able to re-format the dates in Excel you need to export the “serial date/time” value used by Excel. This is the fractional number of days since the mythical 0-Jan-1900 epoch.

Unix timestamps are in UTC (GMT), so the first thing we need to do is convert to local time by adding the UTC to local time difference. This is complicated by the time difference varying for daylight saving. Fortunately, the PHP date function will provide this value in seconds for a given date:

date('Z',$localdate)

As the Unix timestamp is the number of seconds since a certain date, we need to convert that number to days. This is done by dividing by the number of seconds in a day: 24 x 60 x 60 = 86400.

Finally we need to add the number of days in the 70 years between the serial date/time epoch and the unix timestamp epoch of 01-01-1970. Allowing for leap years, this comes to 25569 days. (This can be verified by entering 01-01-1970 into an Excel cell, and formatting the cell as “General”.)

Putting all this together gives a function like this:

And for completeness, here’s a function to go back the other way and convert Excel dates to Unix dates:

Leave a Reply