Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identifiy date string vs date object

In CF10, how can I identify whether an object is a date string or a date object?

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

I have tried isDate(), isValid( 'date' ), isValid( 'string'). All these functions give the same answers ('YES') to both variables. However, lsParseDateTime( myDateObject ) throws an error, so I need to check on the object type before I run the lsParseDateTime function on it.

ps. parseDateTime( myDateObject ) works fine which leads me to wonder if lsParseDateTime is not supposed to throw an error. In Railo 4.2, lsParseDateTime( myDateObject ) works fine.

like image 902
user2943775 Avatar asked Dec 11 '22 23:12

user2943775


2 Answers

You can leverage the fact that all CFML objects are also Java objects, and use Java methods:

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

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

This yields:

java.lang.String
coldfusion.runtime.OleDateTime
like image 187
Adam Cameron Avatar answered Dec 31 '22 17:12

Adam Cameron


Another option is using isInstanceOf(obj, "typeName") with either coldfusion.runtime.OleDateTime or java.util.Date (super class):

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

IsInstanceOf offers greater flexibility, as it allows checking of inherited classes as well. However, keep in mind the function is a bit more heavyweight than comparing the string class name.

Update:

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

It depends on your POV. According to the 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. So if ParseDateTime were strictly adhering to the rules, it would not work either.

That said, most CF date functions accept both date objects and date strings, so unless there are some practical limitations, LSParseDateTime should probably accept date objects too.

like image 38
Leigh Avatar answered Dec 31 '22 15:12

Leigh