Unix time conversion

My question is around Unix/epoch timestamps.

I created some code to turn e.g. 1618617600000 into YYYY-MM-DD HH:MM:SS format:

function td_date2($unix_m) {
	try {
	$unix = $unix_m/1000;
	$datetime = new DateTime("@$unix");
	// Display GMT datetime
	return $datetime->format('Y-m-d H:i:s');
	} catch (Exception $e) {
    return null;

However, the output on the front end comes out as NaN:NaN:NaN if the original unix number doesn’t end in zeros e.g 1631833199999. When you convert this number into date/time, the time portion is 00:00:54.999 so I think the .999 at the end is what’s causing the problem but I’m not sure how to change my code to get rid of this, if indeed this is the right thing to do. Sorry, I’m new to coding so trying my best and I hope this makes sense. Many thanks in advance.

Where does


come from? Why is it divided by 1000 before converting? Sorry if I’m being thick.

Are you wanting to specify times with a microsecond format? If not, just intval() your division so that it drops the decimal. After you specify a time and divide it by 1000, you get that .999. Well datetime doesn’t recognize hundredths… now if you want milliseconds, that would be 4 9’s… aka .9999. If you want microseconds, that is 6 9’s… .999999

But often times people just want to convert the epoche which is whole seconds and thus if you drop the decimal it should work fine. :slight_smile:

Honestly I am seeing some really bad inconsistencies in this the datetime method of converting decimal values. I would stick with whole seconds myself.

Update: Strangely enough it looks like they might have fixed it in PHP 8. PHP 7.4.13 and below appears to be broken. Weird. Based on PHP 8 change log, they have been working on fixing bugs in the date time object around microseconds and such. The bugs they were addressing appear unrelated to this, but perhaps their fixes for those bugs fixed this issue as well.

Thank you so much for your time getting back to me. Your suggestion works perfectly :slight_smile:
Also appreciate you taking the time to explain as well, really helpful. Thank you.

Not at all, perfectly valid question. I’m importing from an external third-party source into a pre-made theme so need to change the dates programmatically. If I don’t divide by 1,000 it comes out as NaN:NaN:NaN on the front end.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.