快速搜索没有返回任何似乎适合我正在寻找的结果,所以我来这里寻求您的帮助。
我正在努力格式化生日。问题是,使用只能输入部分(或不输入(数据。它分别存储为日、月和年。
基本上,根据存在的数据将确定日期的格式和显示回用户的方式。
我的方法是:
#prepare birthday
$bday = new DateTime();
$bday->setTimezone(new DateTimeZone('America/New_York'));
$bday->setDate($row->birth_year,$row->birth_month,$row->birth_day);
if($row->birth_month && $row->birth_year && $row->birth_day){
//Full birthday entered
$display_bday = $bday->format('F j, Y');
} elseif($row->birth_month && !$row->birth_year && !$row->birth_day){
//Only a month
$display_bday = $bday->format('F');
} elseif($row->birth_month && $row->birth_year && !$row->birth_day){
//Only Month and year
$display_bday = $bday->format('F, Y');
}
我想知道是否有更好的方法来完成这项任务。我想我想一定有更好的方法。提前谢谢。如果我需要澄清任何事情,请问!
编辑:删除了不必要的代码
您的代码可能会输出无效的日期,因为在设置 DateTime
对象时不会过滤输入。当$row->birth_day
等于 0
时,DateTime
对象将移回上个月(上一个日期(。
因此,我建议考虑一下:
$display_bday = null;
if ($row->birth_month) {
if ($row->birth_year) {
if ($row->birth_day) {
// day, month, and year
$display_bday = date('F j, Y', strtotime("$row->birth_year-$row->birth_month-$row->birth_day"));
} else {
// month and year
$display_bday = date('F, Y', strtotime("$row->birth_year-$row->birth_month-01"));
}
} else {
if ($row->birth_day) {
// day and month
$display_bday = date('F j', strtotime("2016-$row->birth_month-$row->birth_day"));
} else {
// month only
$display_bday = date('F', strtotime("2016-$row->birth_month-01"));
}
}
}