Neokoenig
Neokoenig

Reputation: 1102

Create DateTime From datepicker string (coldfusion)

In ColdFusion 10:

I'm trying to return a valid datetime string from a string which comes from a datepicker.

The string format is:

15 Aug 2014 - 12:47 PM

And I want to end up with:

{ts '2014-08-15 12:47:00'}

I've written this horrible function to get each part of the string and attempt to createDateTime() :

public function formatDateTimeFromPicker(required string thedate){
    var c={};
    var d=arguments.thedate;
        c.year=listGetAt(d, 3, " ");
        c.month=returnMonthAsNumber(listGetAt(d, 2, " "));
        c.day=listGetAt(d, 1, " ");
        c.time=listGetAt(d, 5, " ");
        c.hour=listGetAt(c.time, 1, ":");
        c.minute=listGetAt(c.time, 2, ":");
        c.tt=listGetAt(d, 6, " ");
        if(c.tt == "PM" AND c.hour NEQ 12){
            c.hour=(c.hour + 12);
        }
        return createDateTime(c.year, c.month, c.day, c.hour, c.minute, 00);
}

public function returnMonthAsNumber(required string monthstring){
    var months="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
        return listFindNoCase(months, arguments.monthstring);
}

It sort of works, but surely there's a better way of doing this??

Upvotes: 0

Views: 409

Answers (1)

Adam Cameron
Adam Cameron

Reputation: 29870

You're possibly over-thinking it. The only thing that stops it parsing as a date as-is is the dash. So get rid. Proof of concept:

original = "15 Aug 2014 - 12:47 PM";
dateString = replace(original, "-", "", "ONE");  
try {
    date = parseDateTime(dateString);
} catch (any e){
    date = e.message;
}
writeDump([original,dateString,date]);
writeOutput(date);

Output:

15 Aug 2014 - 12:47 PM

15 Aug 2014 12:47 PM

August, 15 2014 12:47:00

{ts '2014-08-15 12:47:00'}

Upvotes: 6

Related Questions