The following post shares a code snippet that you can use to sanitize a date time value before saving it in a field or passing it to a query.
It uses two functions one to sanitize and one two validate, first we pass the value through a few sanitize checks then we check if it is actually in the format we want. If the checks fail somewhere we pass back a default time, this could be also an empty string or whatever value your consumer function is trained to handle.
<?php
/**
* Sanitizes date time input
* https://www.lehelmatyus.com/1416/sanitize-date-time-value-in-wordpress
*
* @return String
*/
public sanitize_event_time($event_time) {
// General sanitization, to get rid of malicious scripts or characters
$event_time = sanitize_text_field($event_time);
$event_time = filter_var($event_time, FILTER_SANITIZE_STRING);
// Validation to see if it is the right format
if (_my_validate_date($event_time)){
return $event_time;
}
// default value, to return if checks have failed
return "5:00 am";
}
/**
* Validates that a date string is in the right format
* default format is 'g:i a' to test for time only in this format '5:00 am'
* but you can pass a new format to test against other formats
* other formats here https://www.lehelmatyus.com/1003/android-change-date-format-from-utc-to-local-time
*
* @return bool
*/
function _my_validate_date($date, $format = 'g:i a') {
// Create the format date
$d = DateTime::createFromFormat($format, $date);
// Return the comparison
return $d && $d->format($format) === $date;
}
/**
* To use the code written above just call the function
*/
// $date = ...
$sanitized_date = sanitize_event_duration($date);
If you are looking for other Date formats you can find it here Date Format Strings.
If you are looking for just Changing one format to another in PHP, you can find it here PHP change date format.
I hope this helped, Cheers!