如何从 PHP 中包含不同格式的文件中格式化日期?
How to format dates from a file containing different formats in PHP?
我有一个 excel 文件,其中有多种格式的日期,没有特定的顺序。
格式各不相同
dd/mm/yyyy
dd/mm/yy
dd.mm.yyyy
dd.mm.yy
dd-mm-yyyy
dd-mm-yy
dd.Jan.18
dd-Jan-2018
我遍历 excel 行并逐一获取日期。如何将这些日期转换为特定格式?
最好是 yyyy-mm-dd
我正在使用 PHP 并在处理后将日期存储到 mysql。
我试过这个方法,但对dd.mm.yy
无效
$date = $row[$datepos];
$date = str_replace('/', '-', $date);
$date = date("Y-m-d",strtotime($date));
你可以试试这个。
$date=date_create(传递 excel 中的日期);
date_format($日期,"Y/m/d H:i:s");
如果这些是您必须处理的 只有 个日期,则以下代码将起作用:
$dates = [
"01/01/2018",
"01/01/18",
"01.01.2018",
"01.01.18",
"01-01-2018",
"01-01-18",
"01.Jan.18",
"01-Jan-18",
];
foreach($dates as $date){
$dt_array = preg_split("/[^A-Za-z0-9]/", $date);
//Break apart the date string using any non-alphanumeric character as the delimiter
var_dump($dt_array);
//Just for demonstration purposes
$day = $dt_array[0];
// Grab the day
if(is_numeric($dt_array[1])){
$month = $dt_array[1];
} else {
$dp = date_parse($dt_array[1]);
$month = $dp['month'];
}
//The month is a little bit more complex,
//because at times it's an integer, at times it's a string,
//and we want it to always be a integer
$year = $dt_array[2];
//Grab the year
$dt = new DateTime("{$year}-{$month}-{$day}");
//The y-m-d format is flexible,
//because it will accept yyyy and yy
//and since your m and d are integers,
//it will work even if they don't have a leading zero.
var_dump($dt->format('Y-m-d'));
//Just for demonstration purposes
}
我有一个 excel 文件,其中有多种格式的日期,没有特定的顺序。 格式各不相同
dd/mm/yyyy
dd/mm/yy
dd.mm.yyyy
dd.mm.yy
dd-mm-yyyy
dd-mm-yy
dd.Jan.18
dd-Jan-2018
我遍历 excel 行并逐一获取日期。如何将这些日期转换为特定格式? 最好是 yyyy-mm-dd 我正在使用 PHP 并在处理后将日期存储到 mysql。
我试过这个方法,但对dd.mm.yy
无效$date = $row[$datepos];
$date = str_replace('/', '-', $date);
$date = date("Y-m-d",strtotime($date));
你可以试试这个。
$date=date_create(传递 excel 中的日期); date_format($日期,"Y/m/d H:i:s");
如果这些是您必须处理的 只有 个日期,则以下代码将起作用:
$dates = [
"01/01/2018",
"01/01/18",
"01.01.2018",
"01.01.18",
"01-01-2018",
"01-01-18",
"01.Jan.18",
"01-Jan-18",
];
foreach($dates as $date){
$dt_array = preg_split("/[^A-Za-z0-9]/", $date);
//Break apart the date string using any non-alphanumeric character as the delimiter
var_dump($dt_array);
//Just for demonstration purposes
$day = $dt_array[0];
// Grab the day
if(is_numeric($dt_array[1])){
$month = $dt_array[1];
} else {
$dp = date_parse($dt_array[1]);
$month = $dp['month'];
}
//The month is a little bit more complex,
//because at times it's an integer, at times it's a string,
//and we want it to always be a integer
$year = $dt_array[2];
//Grab the year
$dt = new DateTime("{$year}-{$month}-{$day}");
//The y-m-d format is flexible,
//because it will accept yyyy and yy
//and since your m and d are integers,
//it will work even if they don't have a leading zero.
var_dump($dt->format('Y-m-d'));
//Just for demonstration purposes
}