Search code examples
datetimecoldfusioncoldfusion-9

How to createDateTime from passed arguments date and time?


I have form where user can pick start/end date and time, after from is submitted I want to create createDateTime and use passed arguments. So I tried this way but I got only date stored in my DB. Here is my code:

<cfargument name="DateFrom" type="date" required="yes">
<cfargument name="DateTo" type="date" required="yes">
<cfargument name="TimeFrom" type="string" required="yes">
<cfargument name="TimeTo" type="string" required="yes">

<cfset StartDateTime = createDateTime(year(arguments.DateFrom), month(arguments.DateFrom), day(arguments.DateFrom), hour(arguments.TimeFrom), minute(arguments.TimeFrom), 0)>
<cfset EndDateTime = createDateTime(year(arguments.DateTo), month(arguments.DateTo), day(arguments.DateTo), hour(arguments.TimeTo), minute(arguments.TimeTo), 0)>

 <cfquery name="addReservation" datasource="test">
    Insert Into tableReserv(PickDateTime,DropDateTime)
    Select <cfqueryparam cfsqltype="cf_sql_date" maxlength="12" value="#StartDateTime#">,
            <cfqueryparam cfsqltype="cf_sql_date" maxlength="12" value="#EndDateTime#"> 
    Where Not Exists(Select UserID
                     From aviRequests
                     Where PickDateTime < <cfqueryparam cfsqltype="cf_sql_timestamp" value="#StartDateTime#">
                     And DropDateTime > <cfqueryparam cfsqltype="cf_sql_timestamp" value="#EndDateTime#">
                     )
    Select SCOPE_IDENTITY() As RecID;
</cfquery>

For some reason my StartDateTime and EndDateTime do not create date and time together. Here is how my value looks stored in DB: Start:2016-01-20 00:00:00.000 End:2016-01-21 00:00:00.000 Is my createDateTime properly formatted or something else is wrong in my code?


Solution

  • This is from your question:

    <cfset StartDateTime = createDateTime(year(arguments.DateFrom)
    , month(arguments.DateFrom)
    , day(arguments.DateFrom)
    , hour(arguments.TimeFrom)
    , minute(arguments.TimeFrom), 0)>
    

    The date part is fine because your date arguments are dates. The time part is not because your time arguments are strings. You have to process that string to get the hours and minutes.

    In the comments, you said your time strings resemble 7 AM. You have to process this to get the correct number of hours and minutes. Things you have to consider are:

    • Are the last two characters AM or PM?
    • Does the number of hours have 1 or 2 digits?
    • If it's not at the top of the hour, how are minutes represented?

    Having said all that, you are probably not the first person to have this problem. Look at cflib.org to see if there a function you can use.