PHP Match dates which may differ a few seconds from each other

At my work, I needed to compare two CSV files containing CDR’s (Call Detail Records). To made it quick and easy, I made a PHP script to do this.

Some CDR’s were missing in our file or vice versa. The CDR’s which were not missing needed to be compared with each other. The problem was that I could only match on the phone numbers and the dates. The phone numbers will always be the same, but the other CSV contained CDR’s which dates deviates from the dates in the other file. To make sure I got the right CDR’s to match, I made a method which could match on dates which may deviate a few seconds:

function datesMatch($dateOne, $dateTwo) {	
	$dateOne = trim($dateOne);
	$dateTwo = trim($dateTwo);

	if(is_numeric($dateOne) && is_numeric($dateTwo)) {	
		$dateOne = new DateTime(substr($dateOne, 0, 4).'-'.substr($dateOne, 4, 2).'-'.substr($dateOne, 6, 2).' '.substr($dateOne, 8, 2).':'.substr($dateOne, 10, 2).':'.substr($dateOne, 12, 2));
		$dateTwo = new DateTime(substr($dateTwo, 0, 4).'-'.substr($dateTwo, 4, 2).'-'.substr($dateTwo, 6, 2).' '.substr($dateTwo, 8, 2).':'.substr($dateTwo, 10, 2).':'.substr($dateTwo, 12, 2));

		$difference = $dateOne->diff($dateTwo);

		if(		$difference->y == 0 && 
				$difference->m == 0 && 
				$difference->d == 0 &&
				$difference->h == 0 &&
				$difference->i == 0 &&
				$difference->s <= 4
			) {
			return true;

	return false;

The ‘4’ in this case shows that I allow dates to deviate 4 seconds from each other. This means that $dateOne may be four seconds in the past or in the future, compared with $dateTwo and vice versa. The $difference variable is actually a DateInterval class.

By the way, I had to check if the date variables were numeric, since the data in the CSV files was not that consistent.

I hope this will be useful for you too. 🙂