Coldfusion 10 DateFormat Issue

笑着哭i 提交于 2019-11-29 08:32:18

I disagree with the other answer. The real cause of the problem is that DateFormat is not designed to handle non-US date strings.

The standard CF date functions always use U.S. date parsing rules. That means when you pass in an ambiguous date string, like 01-05-2013, it is parsed according to U.S. English date conventions. In this case, month first ie "mm-dd-yyyy". So the result will always be January 5th, not May 1st.

In some cases you get lucky. With the string 15-05-2013, there is obviously no 15th month, so CF/java must swap the month and day automatically, rather than throwing an error. That is why it seems to handle some dd-mm-yyyy date strings correctly, but not others.

If you want to parse non-US date strings, you should use the LS (Locale Sensitive) date functions instead. However, according to the docs dashes ie "-" are not a standard date separator in most non-US locales: only Dutch and Portuguese (Standard). So you would either need to change the separator OR use one of those two locales when parsing the date:

        lsDateFormat( myDate, "yyyy-mm-dd", "pt_PT")

Side note:

As an aside, DateFormat does expect a date object. However, like most functions in CF it is flexible enough to accept a date string as well. That allows you to use it as a lazy shortcut to convert from date string => date object => then back to (formatted) date string again. Using date objects is preferable (and you really should validate date strings as well) but that is another conversation altogether ...

The problem is that DateFormat expects a date object, and returns a string.

You're passing it a string, not a date. What you want to do is firstly turn your string (of 01-05-2013 etc) into a date object.

To do this I'd recommend using either ParseDateTime or LSParseDateTime, and/or LSDateFormat.

e.g.

<cfset originalDateString = "01-05-2013">

<!--- turn that into a Date --->
<cfset dateObject = ParseDateTime(originalDateString)>

<cfset newdateString = DateFormat(dateObject, "yyyy-mm-dd")>

Alternatively, if you know your string is always in a dd-mm-yyyy format, you could parse the string yourself, e.g. treat it as a list delimited by hyphens.

<cfset dd = listFirst(originalDateString, "-")>
<cfset mm = listGetAt(originalDateString, 2, "-")>
<cfset yy = listLast(originalDateString, "-")>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!