Determing if Datetime or Timestamp

I’m slowly converting all my sites over from the Unix Timestamp to MySQL Datetime and in the process I need a way to determine which it is so that the sites do not break or crash while working on them. For the most part it is working but every so often, a Unix Timestamp is mis-read as a MySQL Datetime so gives odd results.

One Unix Timestamp in particular that is being mis-read is 1643498282 which is being shown as Saturday, October 7th, 8282 while most if not all others are correct. However, 1643498282 is apparently a valid Timestamp for Saturday, January 29th, 2022. Any ideas how to better detect which date type it is?

The function for detecting the type is below and is being called by the function following it.

// DETERMINE WHETHER TIMESTAMP OR DATETIME
// RETURNS TRUE IF MYSQL DATETIME; OTHERWISE FALSE
function isDateTime($value) {
	return (strtotime($value) !== FALSE);
}
// PROVIDES READABLE FORMATTED DATE FOR ON-SCREEN DISPLAY
// WORKS WITH BOTH UNIX TIMESTAMP AND MYSQL DATETIME
function lastUpdated($UpdateDate) {
	$DateFormat = "l, F jS, Y";
	if ($UpdateDate):
		if (isDateTime($UpdateDate)) :
			// FOR MYSQL DATETIME FIELD VALUE
			$FormattedDate = "Last updated on " . date($DateFormat, strtotime($UpdateDate));
		else :
			// FOR UNIX TIMESTAMP FIELD VALUE
			$FormattedDate = "Last updated on " . date($DateFormat, $UpdateDate);
		endif;
	else:
		$FormattedDate = "Today is " . date($DateFormat);
	endif;
  return $FormattedDate;
}

Answering myself as I had already tried this and got some odd results but it seems to work now when checked in conjunction with strtotime($value). Adding checking if the field is numeric fixed it but when I tried it before using that alone, MySQL Datetime seemed to also show as numeric

// DETERMINE WHETHER TIMESTAMP OR DATETIME
// TRUE IF MYSQL DATETIME; OTHERWISE FALSE
function isDateTime($value) {
	return (strtotime($value) !== FALSE && !is_numeric($value));
}

strtotime() is a parser not validator tho

Yes, I know but if the input is not a valid datetime, it gives a False which is what I was looking for. In this case by itself, it works 99.9% of the time but I added additional checking for the remaining .1%. I do have another checking function that compares epoch dates to determine if it’s a Timestamp and it works too but a bit too cumbersome when a single line should do the job.

Sponsor our Newsletter | Privacy Policy | Terms of Service