Vikas
Vikas

Reputation: 24332

ColdFusion: How to parse dd/mm/yyyy formated date?

I found the ParseDateTime function but it only parses a date/time string according to the English (U.S.) locale conventions.

How to parse the date which is in dd/mm/yyyy format?

Try out this:

<cfset TestdateFrom = ParseDateTime("10/9/2010") />
<cfloop index="i" from="1" to="30" step="1">
    <cfset TestdateFrom = DateAdd( "d", 1, TestdateFrom ) />
    #TestdateFrom#<br/>
</cfloop>

In CF9 there is a LSParseDateTime function.

I don't know whether this will help me or not.

At last should I use java library for this issue?

Upvotes: 4

Views: 7382

Answers (4)

ale
ale

Reputation: 6430

If your format is consistent, you can also do something like this:

<cfset dy=listGetAt(dateString,1,"/")>
<cfset mo=listGetAt(dateString,2,"/")>
<cfset yr=listGetAt(dateString,3,"/")>

<cfset myDate=createDate(yr,mo,dy)>

But, really, Tim's answer is the best.

Upvotes: 5

TimDawe
TimDawe

Reputation: 341

I've had success with this technique for dealing with (UK formatted) dates entered as free text:

<cfset SetLocale("English (UK)")>
<cfset valid = true>

<!--- Convert DD-MM-YYYY or DD.MM.YYYY to DD/MM/YYYY --->
<cfset dt = replacelist(dt, ".,-", "/,/")>

<!--- count date elememnts (must be 3 - LSParseDateTime will make potentially incorrect assumptions otherwise) --->
<cfif listlen(dt, "/") neq 3>
    <!--- wrong number of elements --->
    <cfset valid = false>
<cfelse>
    <!--- Correct number of elements so try to interpret as date/time object --->   
    <cftry>
        <cfset dt = LSParseDateTime(dt)> 
        <cfcatch type="Expression">
            <cfset valid = false>
        </cfcatch>
    </cftry>
</cfif>

If valid is true at the end of this, the string date representation in dt has been converted to a date/time object. The replacelist step allows for the date to be entered as DD.MM.YYYY or DD-MM-YYYY as well as DD/MM/YYYY.

Upvotes: 3

Stephen Moretti
Stephen Moretti

Reputation: 2438

You need to use lsParseDateTime(). This is the locale specific date parser.

You can either pass a locale straight into the second parameter of the function or use setlocale() to set it for the request.

You'll probably find it useful to look at the other LS prefixed functions too.

Upvotes: 3

Vikas
Vikas

Reputation: 24332

Looks like this is working:

<cfset formatter = createObject("java","java.text.SimpleDateFormat")>
<cfset formatter.init("dd/MM/yyyy")>
<cfset newDate = formatter.parse("10/09/2010")>
#newDate#

Any other suggestions?

Upvotes: 7

Related Questions