Tribe__Date_Utils::datetime_from_format( string $format, string $date )
As PHP 5.2 doesn’t have a good version of date_parse_from_format, this is how we deal with possible weird datepicker formats not working
Contents
Parameters
- $format
-
(string) (Required) The weird format you are using
- $date
-
(string) (Required) The date string to parse
Return
(string) A DB formated Date, includes time if possible
Source
File: src/Tribe/Date_Utils.php
public static function datetime_from_format( $format, $date ) {
// Reverse engineer the relevant date formats
$keys = array(
// Year with 4 Digits
'Y' => array( 'year', '\d{4}' ),
// Year with 2 Digits
'y' => array( 'year', '\d{2}' ),
// Month with leading 0
'm' => array( 'month', '\d{2}' ),
// Month without the leading 0
'n' => array( 'month', '\d{1,2}' ),
// Month ABBR 3 letters
'M' => array( 'month', '[A-Z][a-z]{2}' ),
// Month Name
'F' => array( 'month', '[A-Z][a-z]{2,8}' ),
// Day with leading 0
'd' => array( 'day', '\d{2}' ),
// Day without leading 0
'j' => array( 'day', '\d{1,2}' ),
// Day ABBR 3 Letters
'D' => array( 'day', '[A-Z][a-z]{2}' ),
// Day Name
'l' => array( 'day', '[A-Z][a-z]{5,8}' ),
// Hour 12h formatted, with leading 0
'h' => array( 'hour', '\d{2}' ),
// Hour 24h formatted, with leading 0
'H' => array( 'hour', '\d{2}' ),
// Hour 12h formatted, without leading 0
'g' => array( 'hour', '\d{1,2}' ),
// Hour 24h formatted, without leading 0
'G' => array( 'hour', '\d{1,2}' ),
// Minutes with leading 0
'i' => array( 'minute', '\d{2}' ),
// Seconds with leading 0
's' => array( 'second', '\d{2}' ),
);
$date_regex = "/{$keys['Y'][1]}-{$keys['m'][1]}-{$keys['d'][1]}( {$keys['H'][1]}:{$keys['i'][1]}:{$keys['s'][1]})?$/";
// if the date is already in Y-m-d or Y-m-d H:i:s, just return it
if ( preg_match( $date_regex, $date ) ) {
return $date;
}
// Convert format string to regex
$regex = '';
$chars = str_split( $format );
foreach ( $chars as $n => $char ) {
$last_char = isset( $chars[ $n - 1 ] ) ? $chars[ $n - 1 ] : '';
$skip_current = '\\' == $last_char;
if ( ! $skip_current && isset( $keys[ $char ] ) ) {
$regex .= '(?P<' . $keys[ $char ][0] . '>' . $keys[ $char ][1] . ')';
} elseif ( '\\' == $char ) {
$regex .= $char;
} else {
$regex .= preg_quote( $char );
}
}
$dt = array();
// Now try to match it
if ( preg_match( '#^' . $regex . '$#', $date, $dt ) ) {
// Remove unwanted Indexes
foreach ( $dt as $k => $v ) {
if ( is_int( $k ) ) {
unset( $dt[ $k ] );
}
}
// We need at least Month + Day + Year to work with
if ( ! checkdate( $dt['month'], $dt['day'], $dt['year'] ) ) {
return false;
}
} else {
return false;
}
$dt['month'] = str_pad( $dt['month'], 2, '0', STR_PAD_LEFT );
$dt['day'] = str_pad( $dt['day'], 2, '0', STR_PAD_LEFT );
$formatted = '{year}-{month}-{day}' . ( isset( $dt['hour'], $dt['minute'], $dt['second'] ) ? ' {hour}:{minute}:{second}' : '' );
foreach ( $dt as $key => $value ) {
$formatted = str_replace( '{' . $key . '}', $value, $formatted );
}
return $formatted;
}