gpt4 book ai didi

php - 提取数据并如果日期将其转换

转载 作者:行者123 更新时间:2023-11-29 13:18:59 24 4
gpt4 key购买 nike

我正在将数据从表中提取到 csv 文件。

当要打印日期字段时,我需要转换为dd/mm/yyyy。这是我尝试过的代码

$result = mysql_query($sqlquery); 
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
$key = trim($value);
$key = str_replace(',', ' ', $key); //remove any commas, as they stuff up excel.
//Is this a date field? if so convert it to dd/mm/yyyy
print "$key" . ",";
}
if ($key > "") fputcsv($output, array(''));
}

最佳答案

最简单的方法是检查值是否为日期格式,因为 mysql_fetch_assoc 不包含字段类型信息。

if(preg_match('/^\d{4}-\d{2}-\d{2}$/',$value)) {
print "$key" . "," . date('d/m/Y',strtotime($value));
}

这会检查 $value 的格式是否为四位数字、破折号、两位数字、破折号和另外两位数字 (yyyy-mm-dd) 的格式,如果是,则使用 strtotime 函数将该值转换为时间戳,日期函数使用它来格式化日期字符串。

顺便说一句,mysql_* 函数已被弃用,您应该使用 mysqli 或 PDO 代替。

关于php - 提取数据并如果日期将其转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21106608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com