coldfusion - parsing a string date into datetime format - coldfusion

We receive an XML file with a date node as follows:
<createdDate>1/11/2008 7:04:28 a.m.</createdDate>
Dates are UK format dd/mm/yyy, so 1/11/2008 is 1st November 2008.
We run a coldfusion function to parse the xml and insert into the database. The relevant database field is of datetime datatype and needs to remain that way. How would I format this string representation of the date into a format the database will accept?

Not an ideal situation, but the format you are getting data especially dots in am/pm strings make it hard to read and on top of that it comes in UK Date format. This can help:
<cfset x="21/11/2008 7:04:28 p.m.">
<cfset x=Replace(x,".","","All")>
<cfset y=LSDateFormat(x,"mm/dd/yyyy","English (UK)")>
<cfoutput>
x====#x#
<br/>y===#y#
<cfset z=CreateDateTime(Year(y),month(y),day(y),hour(x),minute(x),second(x))>
z====#z#
<cfset someDatevare=LSParseDateTime(x,"English (UK)")>
</cfoutput>
EDIT As Leigh mentioned, removing periods or any other non-standard characters from the string and then LSParseDateTime will return a date time object.

Related

Time formatting issue in coldfusion

I am using Taffy framework for creating api endpoints. In one of my endpoint I need to display time in particular format say hh:mm:ss, I used timeformat method in CFC file to get the desired result, but when I hit the endpoint I am getting January, 01 1970 17:00:00. Any suggestions?
Note:For field "clientHoursOfOperationOpenTime" Time value is returned from Mysql, I am querying the DB in CFC file and formatting the clientHoursOfOperationOpenTimevalue.
<cfset var getLocationHours = QueryNew('') >
<cfquery name="getLocationHours" datasource="#appSettings.DSN#">
Select some fields here
</cfquery>
<cfset getLocationHours.clientHoursOfOperationOpenTime= "#timeFormat(getLocationHours.clientHoursOfOperationOpenTime, 'hh:mm:ss')#">
<cfreturn getLocationHours >
When I dump this field getLocationHours.clientHoursOfOperationOpenTime I am getting the formatted value. But when I use taffy, I am getting the format issue.

ColdFusion 11 DateFormat

I am moving one of our applications from ColdFusion 9.01 to ColdFusion 11 and encountered a situation where I cannot get the date formatted the way I want it using "DateFormat". I read through the docs since things have changed in CF versions, but I honestly can't figure out why this isn't working. It worked beautifully in CF 9. I know it's probably something very easy, but I am just not seeing it.
The query (Oracle DB) provides me a list of the last 30 days and the loop is simply to reformat the date output from "2014-07-01 00:00:00.0" to a more friendly looking display of 01-Jul-2014 except that I cannot get it to format as "dd-mmm-yyyy" it just spits back the original output from the query. I hard coded the date where normally there would be a cfquerparam. Any ideas?
<cfquery name="qryDateArray" datasource="#request.db#">
select trunc(to_date('07/01/2014', 'mm/dd/yyyy') + 1 - rownum) as ref_date
from dual connect by rownum <= 30
</cfquery>
<cfloop from="1" to="#qryDateArray.recordcount#" index="j">
<cfset qryDateArray.ref_date[j] = DateFormat(qryDateArray.ref_date[j], "dd-mmm-yyyy")>
</cfloop>
<cfoutput>
<cfdump var="#qryDateArray#">
</cfoutput>
I could not test this on CF11 since I do not have it handy. I did verify that your code though returns results as you explained when I ran it on my CF10 environment here. So what you can do is add a column to the query object and define it as a varchar and add your formatted data to that. This in turn dumped out the formatted dates.
<cfquery name="qryDateArray" datasource="#request.db#">
select trunc(to_date('07/01/2014', 'mm/dd/yyyy') + 1 - rownum) as ref_date
from dual connect by rownum <= 30
</cfquery>
<cfset aryData = [] />
<cfloop from="1" to="#qryDateArray.recordcount#" index="j">
<cfset ArrayAppend(aryData, DateFormat(qryDateArray.ref_date[j], "dd-mmm-yyyy")) />
</cfloop>
<cfset QueryAddColumn(qryDateArray, "STRDATE", "VarChar", aryData) />
<cfoutput>
<cfdump var="#qryDateArray#">
</cfoutput>
If dependent on the query column names then could use something like Ben's method explained here to do some renaming of the columns: http://www.bennadel.com/blog/357-ask-ben-changing-coldfusion-query-column-names.htm
It'd be great if you'd given us a portable test case rather than one that relies on your database, but I suspect it is because ColdFusion has become more rigid with its type management of query columns.
So CF considers your ref_date column to be of type date, so when you try to put the formatted string back into the query column, CF tries (and succeeds) to convert the string back into a date.
Aside:
I have to wonder why you don't format the data string in the DB from the outset, and just return it the way you need it, rather than returning something else, then looping over the thing to adjust it..?

Minimum date for WDDX

I recently had a User enter a data of 6/13/204. SQL Server 2008 happily stored the date. The date was later retrieved and serialized to WDDX. It was encoded as
<field name='BASECYCLEDATE'><dateTime>204-6-13T0:0:0-8:0</dateTime></field>
Later when I deserialized it, I get
WDDX packet parse error at line 1, column 8772..
Invalid date string 204-6-13T0:0:0-8:0.
...
614 : </cfscript>
615 :
616 : <cfwddx action = "wddx2cfml" input = "#qryLabel.Config#" output = "stDat">
My question is, what is the minimum date to deserialize dates in WDDX?
Edit:
To answer your original question, that encoded string is wrong. The serialized dates should be in ISO8601 format, meaning they should have four digit years. A cursory test suggests cfwddx rejects any non-four digit years ie years < 1000 or > 9999.
SQL Server stores the date as 0204.
No, sql server does not store dates as formatted strings. Internally, they are stored as numbers. Ignoring validation for a moment, the cause is strictly on the CF side. When serializing that date into a wddx string, CF fails to generate the leading zero required by ISO8601. So the resulting string 204-6-13T0:0:0-8:0 is malformed and that is why the deserialization fails. That said, since that date range is not valid for your application, you should probably add some validation to reject invalid values like that one.
SQL Server stores the date as 0204. Apparently ColdFusion converts 0204 into 204. If users start doing this often, I will add an additional check to the data coming in. If necessary, I will
<cfif year(basecyledate) LT 1000>
...
</cfif>

Coldfusion 10 DateFormat Issue

I am using the DateFormat function to convert dates to this format: yyyy-mm-dd. This is the original format of the date: dd-mm-yyyy. Below is a snippet of the code:
<cfset newdate = #DateFormat(Trim(mydate), "yyyy-mm-dd")# />
The problem is that I get different results for different dates. For example:
If my original date is: 15-05-2013 (dd-mm-yyyy)
The result is: 2013-05-15 (yyyy-mm-dd)
However, if I change the input and:
The original date is: 01-05-2013 (dd-mm-yyyy)
The result is: 2013-01-05 (yyyy-dd-mm)
Any help or guidance as to what is wrong would be highly appreciated.
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, "-")>

Export to Excel and formatting cells using ColdFusion 10

I have a query which I'd like to output in a spreadsheet in Excel. I'd like some of the cell columns to be formatted in a certain way, which is thousands grouping and in Number format so that sums, additions etc can be done on that row without any further alteration.
I have read through the documentation but it has left me a bit confused on how to output to Excel in the first place.
I started out with a comment but it will be easier to read as an answer.
What have you tried? Have you read through the CFSpreadsheet documentation? Should be pretty straight forward. One of the parameters to the CFSpreadsheet tag is 'query'. Why not start with that and see how it formats the columns for you by default to see what needs tweaking.
Here is an example taken directly from the referenced documentation page:
<cfquery name="courses" datasource="cfdocexamples">
SELECT CORNUMBER, DEPT_ID, COURSE_ID, CORNAME
FROM COURSELIST
</cfquery>
<cfscript>
//Use an absolute path for the files. --->
theDir=GetDirectoryFromPath(GetCurrentTemplatePath());
theFile=theDir & "courses.xls";
//Create an empty ColdFusion spreadsheet object. --->
theSheet = SpreadsheetNew("CourseData");
//Populate the object with a query. --->
SpreadsheetAddRows(theSheet,courses);
</cfscript>
<!--- Write the sheet to a file --->
<cfspreadsheet action="write" filename="#theFile#" name="theSheet" sheetname="courses" overwrite=true>
See the documentation for SpreadsheetFormatColumn, SpreadsheetFormatColumns, SpreadsheetFormatRow and SpreadsheetFormatRows to read about formatting particular cells.
You just need to use the cfspreadsheet tag to create the file, and you can format the cells with the spreadsheetFormat* functions. You can find an example of how to do this at Ray Camden's site.