Reputation: 689
I Have Some Date time String(time stamp) Like Below
2013-03-28 12:12:32
2014-06-28 21:42:12
2015-12-28 07:23:45
2016-02-28 01:19:00
All Of Them Are Valid. But
2011-02-30 25:12:12
this is Not a valid time stamp.
I want check time stamp is valid.
So My Question Is How I validated them.
Upvotes: 0
Views: 2973
Reputation: 450
Using the DateTime class to confirm successful conversion is good practice, but by itself allows for some text strings that would not visually represent a valid DateTime to be successfully converted to a DateTime object.
For example, simply passing in a single letter would not throw an exception, and would return a valid DateTime. For this reason I would recommend pairing the DateTime validation with a regex comparison(s) to ensure that at least the basic expected patterns of a Date/DateTime are present in the string as well. This is especially true if you are working with data from external sources and can't know with certainty what data will be populated, i.e. pulling records from a 3rd party API or database.
// eg: new DateTime('A') produces a valid DateTime object.
function is_datetime($string){
/*
* Adjust RegExp to handle various date formats that you may be expecting
* eg: /[\d]{4,}-[\d]{2,}-[\d]{2,}/ - matches date like 1970-01-01
* eg: /[\d]{2,}:[\d]{2,}:[\d]{2,}/ - matches time like 12:00:00
* combine like (!preg_match($eg1, $string) && !preg_match($eg2, $string))
* for wider coverage/variability in date/time string inputs
*/
if(!preg_match('/[\d]{4,}-[\d]{2,}-[\d]{2,}(.*)[\d]{2,}:[\d]{2,}:[\d]{2,}/', $string))
return false;
try{
new DateTime($string);
return true;
}catch (Exception $e){
return false;
}
}
Upvotes: 0
Reputation: 552
Try this function :
function isValidTimeStamp($timestamp)
{
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX);
}
This check will only return true if the given $timestamp
is a string and consists solely of digits and an optional minus character. The number also has to be within the bit range of an integer.
Saw here
Upvotes: 2
Reputation: 427
You could use DateTime. DateTime will throw an exception if the time string is not valid.
try {
new DateTime('2011-02-30 25:12:12');
} catch (Exception $e) {
// Do something when time string is incorrect
}
Upvotes: 2