PHP Date Conversion: Benchmarking UNIX Timestamp Methods
Back to Blog

PHP Date Conversion: Benchmarking UNIX Timestamp Methods

If I’m given the year, month, day, hour, minute, and second as integers, there are several ways in PHP to convert them into a UNIX timestamp:

// 1. gmmktime() (UTC) → timestamp
$ts1 = (int) gmmktime($hour,$minute,$second,$month,$day,$year);

// 2. mktime() → timestamp
$ts2 = (int) mktime($hour,$minute,$second,$month,$day,$year);

// 3. DateTime → timestamp
$ts3 = (new DateTime("$year-$month-$day $hour:$minute:$second"))->getTimestamp();

// 4. DateTimeImmutable → timestamp
$ts4 = (new DateTimeImmutable("$year-$month-$day $hour:$minute:$second"))->getTimestamp();

// 5. strtotime() → timestamp
$ts5 = (int) strtotime("$year-$month-$day $hour:$minute:$second");

// 6. date_create() → timestamp
$ts6 = date_timestamp_get(date_create("$year-$month-$day $hour:$minute:$second"));

// 7. IntlCalendar → timestamp
$ts7 = (int)(IntlCalendar::createInstance()->set($year,$month-1,$day,$hour,$minute,$second)->getTime()/1000);

I ran a benchmark to compare their performance. The table below shows the average time per execution after running each function 50,000 times.

Methods labeled 1B, 2B, … 7B include a timezone switch before the conversion and then revert to the original timezone afterwards.

Note that the average time is measured in nanoseconds, so all of these methods are actually quite fast unless executed a large number of times.

# Method Name Avg Time (ns) Relative to 1A
1A gmmktime() 336 1.0X
1B gmmktime() + TZ switch 819 2.4X
2A mktime() 662 2.0X
2B mktime() + TZ switch 1968 5.9X
3A DateTime 2088 6.2X
3B DateTime + TZ switch 3650 10.9X
4A DateTimeImmutable 2089 6.2X
4B DateTimeImmutable + TZ switch 3642 10.8X
5A strtotime() 1744 5.2X
5B strtotime() + TZ switch 3089 9.2X
6A date_create() 2119 6.3X
6B date_create() + TZ switch 3637 10.8X
7A IntlCalendar 15865 47.3X
7B IntlCalendar + TZ switch 18277 54.4X