How to fix dates to be similar format?

前端 未结 2 955
滥情空心
滥情空心 2021-01-24 11:04

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

2条回答
  •  难免孤独
    2021-01-24 11:08

    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

    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];
                }
            }
        }
    

提交回复
热议问题