这个日期时间功能可以更有效地编写吗?

时间:2011-05-24 16:31:19

标签: datetime coldfusion

以下函数返回单词中两个日期时间值之间的差异(作为字符串)。可以更有效/更优雅地写出来吗?

/**
* @hint Returns the difference between two time strings in words.
*/
public string function timeAgoInWords(required date fromTime, date toTime=now())
{
    local.secondDiff = dateDiff("s", arguments.fromTime, arguments.toTime);

    if (local.secondDiff <= 60)
        return "#local.secondDiff# seconds ago";

    local.minuteDiff = dateDiff("n", arguments.fromTime, arguments.toTime);

    if (local.minuteDiff <= 60)
        if (local.minuteDiff < 2)
            return "1 minute ago";
        else return "#local.minuteDiff# minutes ago";

    if (local.minuteDiff <= 1440)
        if (local.minuteDiff <= 120)
            return "1 hour ago";
        else return "#int(local.minuteDiff/60)# hours ago";

    if (local.minuteDiff <= 2880)
        return "yesterday";

    if (local.minuteDiff <= 4320)
        return "2 days ago";

    local.monthDiff = dateDiff("m", arguments.fromTime, arguments.toTime);

    if (local.monthDiff <= 12)
        return "#dateFormat(arguments.fromTime, "mmm dd")# at #timeFormat(arguments.fromTime, "h:mm")#";

    return "#dateFormat(arguments.fromTime, "mmm dd 'yy")# at #timeFormat(arguments.fromTime, "h:mm")#";
}

2 个答案:

答案 0 :(得分:3)

这是我几个月前写的,基于上面在评论中发布的UDF Al Everett并用CF9脚本风格编写。它不会更有效率。事实上,它应该比你的实现慢,因为它有多次调用dateDiff(),并且需要预先设置2个数组,但整体行数更短且易于理解。

string function ago(required Date dateThen)
{
    var dateparts = ["yyyy","m","d","h","n"];
    var datepartNames = ["year","month","day","hour","minute"];
    var rightNow = Now();

    for (var i = 1; i <= 5; i++)    // 5 == arrayLen(dateparts)
    {
        var diff = dateDiff(variables.dateparts[i], dateThen, rightNow);

        if (diff > 1)
            return "#diff# #datepartNames[i]#s ago";

        if (diff == 1)
            return "#diff# #datepartNames[i]# ago";
    }

    return "Just Now";
}

答案 1 :(得分:2)

对我来说很好看。您可以使用您的第一个diff(local.secondDiff)进行所有测试而不是重新差异,但这可能更容易阅读。