Convert string to date/time

Moderator: admin

Convert string to date/time

Postby robocod » Thu Jun 14, 2012 7:00 am

I wrote this little function to convert a string format into the internal date/time format.

The function takes a string parameter of the format YYYY/MM/DD HH:MM or YYYY/MM/DD. And it returns the date/time value (OLE format).

If the string was empty it returns 0 and if the format was wrong it returns -1, so can you can differentiate between no date/time specified and wrongly entered date/time.

I used YYYY/MM/DD, since this is less ambiguous (i.e. won't get mixed up with US and European formats, DD/MM/YYYY and MM/DD/YYYY). The time is optional. The time is assumed to be 24 hour clock.

It's not perfect, but better than nothing.

Code: Select all
function getDateTime(s)
    if #s > 0 then
        local yyyy, mm, dd = string.match(s, "(%d%d%d%d)/(%d+)/(%d+)");
        local h, m = string.match(s, "(%d+):(%d%d)");
        if yyyy and mm and dd and h and m then
            return core.datetime(yyyy, mm, dd, h, m, 0)
        elseif yyyy and mm and dd then
            return core.date(yyyy, mm, dd);
        else
            return -1; -- Error case, mal-formatted date/time
        end
    end
   
    return 0; -- No date/time specified
end
User avatar
robocod
FXCodeBase: Graduate
 
Posts: 298
Joined: Thu May 10, 2012 4:25 pm

Return to Indicator Development

Who is online

Users browsing this forum: No registered users and 76 guests

cron