I am receiving 2 date formats:
1/22/2020
1/22/20
I need to convert 1/22/2020
to 1/22/20
I currently use the
You can use php DateTime::createFromFormat function for converting the date in more robust way.
// filter only 4 digit year using regex
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $date)) {
$dateObj = DateTime::createFromFormat('n/d/Y', $date);
if ($dateObj === false) {
throw new Exception("Not a valid date");
}
// convert it to 2 digit year
echo $dateObj->format('n/j/y');
}
Here's how it can apply to your problem
<?php
foreach($header as $field){
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $field)) {
$dateObj = DateTime::createFromFormat('n/d/Y', $field);
if ($dateObj === false) {
throw new Exception("Not a valid date");
}
// convert it to 2 digit year
$field = $dateObj->format('n/j/y');
if($insert){
$days[] = ["date" => $field, $type => $value[$field]];
}
else{
$date_index = array_search($field, array_column($globalData[$index]['data'], 'date'));
$globalData[$index]['data'][$date_index][$type] = $value[$field];
}
}
}
Do you need this:
$str1 = "1/22/2024";
$str2 = "1/22/24";
function get_needed_format($str) {
if(strlen(explode("/", $str)[2]) === 4) {
return substr($str, 0, -4).substr($str, -2);
}
return $str;
}
echo get_needed_format($str1);
echo "\n";
echo get_needed_format($str2);
?