Tuesday, December 4, 2012

Parsing date string

If you are non US user you will stumble on a problem how to parse date strings that are in non US format i.e. 31.12.2012. Code below does just that. First we use regular expression to extract month, date and year and if it is a valid date then convert it to Datetime object.

public function ParseForDateTimeValue ($strText) {
  if ($strText != "") {
    // RegExp taken from php.net
        $strText, $arr_parts)) {

      $month = ltrim($arr_parts[2], '0');
      $day = ltrim($arr_parts[1], '0');
      $year = $arr_parts[3];

      if (checkdate($month, $day, $year)) {
        return new DateTime(date('Y-m-d H:i:s', 
         mktime(0, 0, 0, $month, $day, $year)));
  return NULL;

No comments: