我有以下几年前写的函数。它从我的数据库中获取一个日期时间,并以更好的格式化方式显示它。
function formatTime($dateTime){
// show time only if posted today
if (date('Ymd') == date('Ymd', strtotime($dateTime))) {
$dt = date('g:i a', strtotime($dateTime));
} else {
// if not the same year show YEAR
if (date('Y') == date('Y', strtotime($dateTime))) {
$dt = date('M j', strtotime($dateTime));
} else {
$dt = date('M j, Y', strtotime($dateTime));
}
}
return $dt;
}我使用服务器时间,这对我来说是CST。昨天,我有一位来自澳大利亚的用户指出,自从他走上了一个完全不同的时区,实际上还有一天的时间(与我在特定时间的输出相比:),它就没有任何收益了。
我决定重写我的函数,说这样的话:
<代码>H 1102-7天>#天前<代码>H 211<代码>H 1127天-月>>周前<代码>H 213/代码><代码>H 1141-2个月>一个月以上<代码>H 215/代码>H 116之后,我就可以显示日期<>H 217>。
是否有任何功能您可能知道这样做,如果不是,我将如何修改这个?
谢谢。
发布于 2012-03-19 15:03:36
function formatTime ($dateTime) {
// A Unix timestamp will definitely be required
$dateTimeInt = strtotime($dateTime);
// First we need to get the number of seconds ago this was
$secondsAgo = time() - $dateTimeInt;
// Now we decide what to do with it
switch (TRUE) {
case $secondsAgo < 60: // Less than a minute
return "$secondsAgo seconds ago";
case $secondsAgo < 3600: // Less than an hour
return floor($secondsAgo / 60)." minutes ago";
case $secondsAgo < 7200: // Less than 2 hours
return "over an hour ago";
case $secondsAgo < 86400: // Less than 1 day
return "1 day ago"; // This makes no sense, but it is what you have asked for...
case $secondsAgo < (86400 * 7): // Less than 1 week
return floor($secondsAgo / 86400)." days ago";
case $secondsAgo < (86400 * 28): // Less than 1 month - for the sake of argument let's call a month 28 days
return floor($secondsAgo / (86400 * 7))." weeks ago";
case $secondsAgo < (86400 * 56): // Less than 2 months
return "over a month ago";
default:
return date('M j, Y', $dateTimeInt);
}
}这绝不是完美无缺的,尤其是考虑到您的一个需求没有意义(请参阅注释),但希望它能帮助您朝着正确的方向前进,并说明如何使用switch使您能够轻松地从行为中添加和删除项/选项。
https://stackoverflow.com/questions/9772014
复制相似问题