Reputation: 351
I have a cfm page with a textbox that has inside a date.
The default date is "Now()"
and I can edit it.
In the same page I have some "combobox" that refresh the page when I change the selection. The issue is if I write inside the textbox, for example, "01/05/2013"
after the refresh there will be "05/01/2013"
and after another refresh there will be "01/05/2013"
.
Here some code:
<cfset myDate="">
<cfif isDefined('URL.date') and URL.date neq "">
<cfset myDate="#DateFormat(URL.date, 'dd/MM/yyyy')#">
<cfelse>
<cfset myDate="#DateFormat(Now(), 'dd/MM/yyyy')#">
</cfif>
<cfoutput>
<cfinput type="text" name="date" id="date" style="width:65px; text-align:center" class="input" value="#myDate#">
</cfoutput>
EDIT: on javascript I use to save the date the following code:
var date=document.getElementById("date");
and I refresh the page with:
location.href("myPage.cfm?date="+date.value);
any help? Thanks.
Upvotes: 0
Views: 1250
Reputation: 4446
I believe this is because CF wants to use Month/Day/Year format by default. When you type 1/5/13 CF thinks you mean Jan 5, 2013, so when you use dateformat
to format it to day/month/year you get 5/1/2013, when the page is reloaded with 5/1/2013, CF now thinks you mean May 1, 2013. Each time you reload the page it swaps it back and forth.
If you don't want ColdFusion messing with your date that you input, don't apply the dateFormat
Adobe docs for dateFormat
suggests formatting dates on input is a bad idea.
Note: The DateFormat function is best used for formatting output, not for formatting input. For formatting input, use one of the date/time creation functions (for example, CreateDate) instead.
Upvotes: 2
Reputation: 13548
As Travis stated, by default ColdFusion treats dates with the U.S. format mm/dd/yyyy
. So your example of 01/05/2013
translates to January 5, 2013. Then you re-format that date into dd/mm/yyyy
format as 05/01/2013
. Your JavaScript then assigns this new date to your form field. On resubmission the date is now 05/01/2013
which in US format is May 1, 2013. Then you reformat back to 01/05/2013
and JavaScript updates your form field, and so on.
Since you are wanting to deal with a non-U.S. date format you should use the Locale Specific LSDateFormat()
function instead of DateFormat()
. With it you can specify a format and locale to use.
lsDateFormat( myDate, "dd/mm/yyyy", "en_GB")
Upvotes: 4
Reputation: 20804
url.date is not a date object, it's a string. Therefore this line:
<cfset myDate="#DateFormat(URL.date, 'dd/MM/yyyy')#">
is overengineered. All you need is:
<cfset myDate = URL.date>
This simple change should solve your problem.
Upvotes: 0