问题
I't tyring to insert a time AND date into a table using a form.
<tr>
<td> Date (Please enter date format mm/dd/yyyy.):</td>
<td><INPUT TYPE="text" NAME="date_used" SIZE="10" VALIDATE="date"></td>
</tr>
<tr>
<td> Time (Please enter time format hh:mm tt):</td>
<td><INPUT TYPE="text" NAME="time_used" SIZE="10" VALIDATE="time" ></td>
</tr>
.....
<CFSET date_used = #DateFormat(CREATEODBCDATETIME(date_used), "mm/d/yyyy")#>
<CFSET time_used = #DATEFormat(CREATEODBCTIME(time_used),"h:mm tt")#>
But when I insert it into the table I get a error
"Conversion failed when converting date and/or time from character string."
Which is on the line im inserting the time_used into the table. Is there a better way to insert a specific time and date into a table?
回答1:
First of all Dateformat and TimeFormat return strings and you want a datetime object. The way to get that is with ParseDateTime.
<cfset YourDateTime =
ParseDateTime(form.Date_used & ' ' & form.time_used, 'mask goes here')>
Then in your query, use the cfsqltype attribute of cfqueryparam to separate the date and time.
insert into table (datefield, timefield)
values
(<cfqueryparam cfsqltype="cf_sql_date" value="#YourDateTime#">
, <cfqueryparam cfsqltype="cf_sql_time" value="#YourDateTime#">
)
You can look up the mask to use for ParseDateTime().
Those are the basics. You will have to do a lot of input validation of course. You might also want to verify that it's necessary to make users enter the seconds portion of the time.
来源:https://stackoverflow.com/questions/24271110/how-to-correctly-insert-time-and-date-into-a-table