0

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.

ABHIJIT
  • 627
  • 4
  • 16
  • This might help http://php.net/manual/en/datetime.createfromformat.php – Alon Eitan Feb 17 '16 at 17:52
  • By reading the documentation for [**`strtotime()`**](http://php.net/manual/en/function.strtotime.php) – MonkeyZeus Feb 17 '16 at 17:52
  • How did you get 25:12:12? I would try to improve user interface (e.g put proper html input fields like > ) rather than validate it on server. – Johnny Feb 17 '16 at 17:53

3 Answers3

1

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
}
Kurzyx
  • 372
  • 3
  • 14
1

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

Community
  • 1
  • 1
Kariamoss
  • 542
  • 1
  • 9
  • 29
0

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;
   }
}
KFish
  • 440
  • 3
  • 9