如何识别日期字符串与日期对象

How to identifiy date string vs date object

在CF10中,如何识别对象是日期字符串还是日期对象?

myDateString = '2015-05-05';
myDateObject = createDate( 2015, 5, 5 );

我试过 isDate()、isValid('date')、isValid('string')。所有这些函数对两个变量给出相同的答案 ('YES')。但是,lsParseDateTime( myDateObject ) 会抛出错误,因此我需要在 运行 对其上的 lsParseDateTime 函数之前检查对象类型。

ps。 parseDateTime( myDateObject ) 工作正常,这让我想知道 lsParseDateTime 是否不应该抛出错误。在 Railo 4.2 中,lsParseDateTime( myDateObject ) 工作正常。

您可以利用所有 CFML 对象也是 Java 对象这一事实,并使用 Java 方法:

myDateString = '2015-05-05';    
myDateObject = createDate( 2015, 5, 5 );    

writeOutput(myDateString.getClass().getName());    
writeOutput("<br>");    
writeOutput(myDateObject.getClass().getName());    

这产生:

java.lang.String
coldfusion.runtime.OleDateTime

另一种选择是将 isInstanceOf(obj, "typeName")coldfusion.runtime.OleDateTimejava.util.Date 一起使用(超级 class):

   isInstanceOf(myDateObject, "coldfusion.runtime.OleDateTime");    
   isInstanceOf(myDateObject, "java.util.Date"); 

IsInstanceOf 提供了更大的灵活性,因为它也允许检查继承的 classes。但是,请记住,该函数比比较字符串 class 名称更重量级。

更新:

leads me to wonder if lsParseDateTime is not supposed to throw an error

这取决于你的视角。根据documentation, LSParseDateTime uses "..Java standard locale formatting rules on all platforms" and expects a date string "...in a format that is readable in the current locale". ParseDateTime has similar rules, except it only uses English (U.S.) locale conventions. When a CF date object is implicitly converted to a string, it yields a value like {ts '2015-05-18 16:06:10'}. Technically that is NOT a "parseable" string according the standard conventions。所以如果 ParseDateTime 严格遵守规则,它也行不通。

也就是说,大多数 CF 日期函数都接受日期对象和日期字符串,因此除非有一些实际限制,否则 LSParseDateTime 应该也接受日期对象。