4

我正在使用一个以 ISO 8601 格式显示日期和时间的脚本,如下所示2012-05-17T17:35:44.000Z

但我希望它在使用#Now()#符号时以正常的 ColdFusion 时间戳格式显示......所以以这种格式:{ts '2012-05-17 17:35:44'}

我怎样才能做到这一点?

4

6 回答 6

5

从 CF 10 开始, parseDateTime直接支持 ISO-8601 。

<cfset string = "1997-07-16T19:20:30+01:00">
<cfset date = parseDateTime(string, "yyyy-MM-dd'T'HH:mm:ssX")>

TryCF.com 上的可运​​行示例

于 2016-11-16T20:36:26.470 回答
2

很确定只是一个解析然后输出会以你想要的格式给你:

#parseDateTime(REReplace("2012-05-17T17:35:44.000Z", "(\d{4})-?(\d{2})-?(\d{2})T([\d:]+).*", "\1-\2-\3 \4"))#

编辑:已修复并经过测试。;)

于 2012-06-08T16:20:50.337 回答
1

我认为这是一个更完整的解决方案和优雅的解决方案:

        <cffunction name="ConvertISOToDateTime" access="private" returntype="date">
    <cfargument name="ISODateString" required="yes" type="string" hint="Properly formed ISO-8601 dateTime String">
    <cfscript>
        // time formats have 2 ways of showing themselves: 1994-11-05T13:15:30Z UTC format OR 1994-11-05T08:15:30-05:00
        local.initial_date = parseDateTime(REReplace(ISODateString, "(\d{4})-?(\d{2})-?(\d{2})T([\d:]+).*", "\1-\2-\3 \4"));
        // If not in UTC format then we need to
        if (right(arguments.ISODateString, 1) neq "Z") {
            local.timeModifier = "";
            //Now we determine if we are adding or deleting the the time modifier.
            if (ISODateString contains '+' and listlen(listrest(ISODateString,"+"),":") eq 2){
                local.timeModifier = listrest(ISODateString,"+");
                local.multiplier = 1; // Add
            } else if (listlen(listlast(ISODateString,"-"),":") eq 2) {
                local.timeModifier = listlast(ISODateString,"-");
                local.multiplier = -1; // Delete
            }
            if (len(local.timeModifier)){
                local.initial_date = dateAdd("h", val(listfirst(local.timeModifier,":"))*local.multiplier,local.initial_date);
                local.initial_date =  dateAdd("m", val(listlast(local.timeModifier,":"))*local.multiplier,local.initial_date);
            }
        }
        return local.initial_date;
    </cfscript>
</cffunction>
于 2012-10-11T10:20:54.997 回答
1

从 CF2016 开始,Tim Sylvester 的回答变成:

<cfset string = "1997-07-16T19:20:30+01:00">
<cfset date = parseDateTime(string, "yyyy-MM-dd'T'HH:nn:ssX")>

mm掩码已被弃用并替换nn为 CF10 和 CF11 不可用。

警告mm掩码行为也随着 CF2016(+ 2018 和 2021)而改变,前面的示例将输出{ts '1998-08-16 18:00:30'}.

于 2022-02-23T17:17:33.713 回答
0

该日期字符串采用 ISO 格式,这里有一个很好的示例说明如何将其转换为 CF 日期对象:

...
<cfreturn ARGUMENTS.Date.ReplaceFirst(
    "^.*?(\d{4})-?(\d{2})-?(\d{2})T([\d:]+).*$",
    "$1-$2-$3 $4"
    ) />
于 2012-05-17T22:38:41.180 回答
0

使用createOdbcDate功能。最好在查询中进行比较。

<cfquery name="GetVisits" >
    SELECT v.ExecutiveID, eu.firstname, eu.lastname from Visits where
v.visitDate between #CreateODBCDate(DateFrom)#
        AND  #CreateODBCDate(DateTo)#
</cfquery>
于 2013-02-17T15:24:44.243 回答