Permalink
Browse files

Merge pull request #241 from kleingeist/master

Adding support for saving the datetime internally as unix timestamp
  • Loading branch information...
2 parents 7bf8cb5 + cdd89a8 commit c9ad967fd48f689f54ec60a88852d6b3f0a91ec6 @rilwis committed Mar 7, 2013
Showing with 53 additions and 2 deletions.
  1. +53 −2 inc/fields/datetime.php
View
55 inc/fields/datetime.php
@@ -39,14 +39,39 @@ static function html( $html, $meta, $field )
return sprintf(
'<input type="text" class="rwmb-datetime" name="%s" value="%s" id="%s" size="%s" data-options="%s" />',
$field['field_name'],
- $meta,
+ isset( $field['timestamp'] ) && $field['timestamp'] ? date(RWMB_Datetime_Field::translateFormat($field), $meta) : $meta,
isset( $field['clone'] ) && $field['clone'] ? '' : $field['id'],
$field['size'],
esc_attr( json_encode( $field['js_options'] ) )
);
}
/**
+ * Calculates the timestamp from the datetime string and returns it
+ * if $field['timestamp'] is set or the datetime string if not
+ *
+ * @param mixed $new
+ * @param mixed $old
+ * @param int $post_id
+ * @param array $field
+ *
+ * @return string|int
+ */
+ static function value($new, $old, $post_id, $field)
+ {
+ if ($field['timestamp']) {
+ $d = DateTime::createFromFormat(RWMB_Datetime_Field::translateFormat($field), $new);
+ if ($d) {
+ return $d->getTimestamp();
+ }
+ return 0;
+ }
+ else {
+ return $new;
+ }
+ }
+
+ /**
* Normalize parameters for field
*
* @param array $field
@@ -58,6 +83,7 @@ static function normalize_field( $field )
$field = wp_parse_args( $field, array(
'size' => 30,
'js_options' => array(),
+ 'timestamp' => false,
) );
// Deprecate 'format', but keep it for backward compatible
@@ -66,9 +92,34 @@ static function normalize_field( $field )
'dateFormat' => empty( $field['format'] ) ? 'yy-mm-dd' : $field['format'],
'timeFormat' => 'hh:mm',
'showButtonPanel' => true,
+ 'separator' => ' ',
) );
return $field;
}
+
+
+
+ // missing: 't' => '', T' => '', 'm' => '', 's' => ''
+ static $timeFormatTranslation = array('H' => 'H', 'HH' => 'H', 'h' => 'H', 'hh' => 'H',
+ 'mm' => 'i', 'ss' => 's', 'l' => 'u', 'tt' => 'a', 'TT' => 'A');
+
+ // missing: 'o' => '', '!' => '', 'oo' => '', '@' => '', "''" => "'"
+ static $dateFormatTranslation = array('d' => 'j', 'dd' => 'd', 'oo' => 'z', 'D' => 'D', 'DD' => 'l',
+ 'm' => 'n', 'mm' => 'm', 'M' => 'M', 'MM' => 'F', 'y' => 'y', 'yy' => 'Y');
+
+ /**
+ * Returns a date() compatible format string from the JavaScript format
+ * @see http://www.php.net/manual/en/function.date.php
+ *
+ * @param array $field
+ *
+ * @return string
+ */
+ static function translateFormat($field) {
+ return strtr( $field['js_options']['dateFormat'], RWMB_Datetime_Field::$dateFormatTranslation)
+ . $field['js_options']['separator']
+ . strtr( $field['js_options']['timeFormat'], RWMB_Datetime_Field::$timeFormatTranslation);
+ }
}
-}
+}

0 comments on commit c9ad967

Please sign in to comment.