How to insert date in a table with a different format? - mysql

My problem here is that I have a date value as 05/09/2013 in a HTML text box which cannot be altered.
Now sql only accepts date format as yyyy/mm/dd. so while inserting this textbox value into sql database it does not support this format and throws an exception.
Therefore my question is how to insert a textbox value with different format into a sql database?
For instance my code would look like
insert into table (date) value('"& date& "')
input box has a calender type textbox and sends a date in 05/09/2013 format

UPDATE
For MySQL use STR_TO_DATE()
INSERT INTO Table1 (date)
SELECT STR_TO_DATE('05/09/2013', '%d/%m/%Y')
SQLFiddle
Based on your comments the query should look like
sql = "INSERT INTO shiftpatterns (siteNumber,shiftdate) SELECT '"&siteNumber&"', 'STR_TO_DATE('"&shiftdate&"','%d/%m/%Y')"
Original answer
For SQL Server use CONVERT
INSERT INTO Table1 ([date])
SELECT CONVERT(datetime, '05/09/2013', 103)
SQLFiddle
In both cases
SELECT * FROM table1
will give you:
| DATE |
------------------------------------
| September, 05 2013 00:00:00+0000 |

According to your tags you're using classic ASP, so we can assume that you're using a form to submit the data to the ASP page you're writing.
The most fault-tolerant way, if you cannot edit the client-side page, is to spool up a date object, parse the supplied value, and then extract your data from there. Or, you could just treat it as a string, test for the expected format, and then maniplate the string into the clearer form.
function fixDate(inStr)
if inStr like '99/99/9999' then
fixDate = LEFT(inStr,4) + "/" + RIGHT(inStr,4)
endif
end function

Related

MySQL "Incorrect DATE value" in SELECT query inside WHERE clause

MySQL version: 8.0.23-0ubuntu0.20.04.1 - (Ubuntu)
When running sample query:
SELECT * FROM `redacted-tbl`
WHERE `redacted-col` = 'some-invalid-date'
ORDER BY `redacted-col` DESC LIMIT 0, 25
data structure: redacted-col DATE
I'm getting #1525 - Incorrect DATE value: 'some-invalid-date' error.
Now I understand that 'some-invalid-date' is definitely not a valid mysql date format. I understand that the error is expected behavior if it's an INSERT or UPDATE query.
But why do I get such error on SELECT query? Previous version of mysql didn't throw such error for SELECT query (only for INSERT/UPDATE).
Also, how do I turn off this error for SELECT-ing DATE column? Is there any mysql flags to disable such check?
Edit (added from my comment):
In my opinion, there are good reasons to allow comparison of non-valid-date-string with DATE columns:
querying with WHERE mydatecol > '2015' to get all date that is after '2015-01-01'
even better, I can just pass user inputted date as filter (sanitized and parameter-bind-ed of course): WHERE mydatecol > ?,
if user enter 2015 then it will become shorthand for user who cares only to get all records after 2015
if user enter 2015-04, then it will become shorthand for user who want records after 2015 month 04/April)
if user enter 2015-04-15 (normal/valid mysql date string), then app will display records after 2015 month 04/April date 15
without this "non-date-validated comparison", I would have to write more application code just to check if the user inputted valid date or not, e.g.:
if the input format is 2015 then I have to change it into 2015-01-01,
else if the input format is 2015-04 then I have to change it into 2015-04-01,
else if the input format is 2015-04-15 then it's valid,
else it's not valid and throw error (or just output current date/default date or just show 'no entry matched your search criteria')
[The text of this answer was originally written by forpas https://stackoverflow.com/users/10498828/forpas ]
You can cast mydatecol to a string to perform the comparison. An easy way to do it is with CONCAT():
WHERE CONCAT(mydatecol) > '2015'
or with cast:
WHERE CAST(redacted-col AS CHAR) > 2015

how to query date in json?

create tabel test(json jsonb);
insert into test values('{"graductionDate": "Jun 1 2015 12:00AM"}')
insert into test values('{"graductionDate": "Jun 1 2016 12:00AM"}')
query result is incorrect:
select * from test where json>'{"graductionDate":"20151001 00:00"}'
I want get data with graductionDate after 20150101. But the above code gets all rows.
http://www.postgresql.org/docs/current/static/functions-json.html
Not having used json objects before I would guess you need to extract the date field from the object, treat it as a date and then compare it to another date.
select *
from test
where ((json->>'graductionDate')::timestamp) > ('20151001 00:00':: timestamp);
I havent tested this code.
Edit
From your comment it sounds like the ->> operator treats null as the empty string ''. You can convert '' to null using the nullif() function:
select *
from test
where (nullif(json->>'graductionDate', '')::timestamp) > ('20151001 00:00':: timestamp);
This code is still untested.

SQL Change date format from yyyy-mm-dd to dd-mm-yyyy

I have created MySQL table :
CREATE TABLE EMP(
EMPID INTEGER NOT NULL (5),
SURNAME VARCHAR(25),
SAL INTEGER(5),
JON VARCHAR(25),
START_DATE DATE,
END_DATE DATE,
DEPNO INTEGER(5)
);
with following records:
INSERT INTO EMP
(EMPID,SURNAME,SALARY,JOB,START_DATE,END_DATE,DEPNO)
VALUES
('1','Vorosila','500000','COO','20150101',null,'1');
however I need to change date format from 2015 01 01 to 01 01 2015
Can anybody show me or tell me how to do that ?
THANK YOU IN ADVANCE
DATE values do not have a "format", they are objects that represent instants in time (or entire days, but still independent of formatting).
Formats are applied on input and output, so you just need to apply the correct format, which you can find in the MySQL manual, to the SELECT statement.
You cannot change the default date format in mysql.
I once hoped for the default date to be editable so I wouldn't have to jump through these hoops to get the date I actually wanted, mysql even has a date format system variable, but it is unused. Date Format Mysql - link
What you should really do is store it as the default format Year-Month-Date and then convert it on select.
The first thing I'd suggest is having your date columns as date types, which would give your dates the following format '2015-01-01'.
If you do this then you can use DATE_FORMAT - link - the second value in the DATE_FORMAT function allows you to customise the returned date, and there are many different thing you can do with this if you look at the link:
SELECT
DATE_FORMAT(`START_DATE`,'%d-%m-%Y')
AS `START_DATE`
FROM ...
The other option you have is to store your dates in the format that you already want as a char or varchar column.
HOWEVER, as should be obvious, this column will not be treated as storing dates, and so will not give you the correct comparisons in a where clause when using > < BETWEEN or the correct ordering in an order by clause. It is after all just a string of numbers in this case.
However you can then use STR_TO_DATE - link if you did need to use a where or order by on this column to change it back to a date within the query - in this case the second value is the custom format of your 'dates' in the column. Keep in mind with a where you will need to compare it with the correct mysql format as shown below:
SELECT
`START_DATE`
FROM table
WHERE STR_TO_DATE(`START_DATE`,'%d-%m-%Y') BETWEEN '2015-01-01' and '2016-01-01'
In MySQL you can change the format of a date using DATE_FORMAT method which is similar to to_char in Oracle.
DATE_FORMAT(SYSDATE(), '%DD-%MM-%YYYY');
For more information about specifiers check this thread http://www.sqlines.com/oracle-to-mysql/to_char_datetime
You can do what you probably want by creating a view and referring to that instead of the (underlying) table.
CREATE VIEW emp_view AS
SELECT empid,
surname,
sal,
jon,
date_format(start_date, '%d-%m-%Y') as start_date,
date_format(end_date, '%d-%m-%Y') as end_date,
depno
FROM emp;
Note that this changes the type of the date columns to varchar, so comparisons will no longer work as expected:
SELECT * FROM emp_view WHERE start_date > '01-12-1924'; // fails!

How to restrict the date in sql

I need a small validation in Sql for from date and to date columns i have.
suppose I have given 01/08/2014 and 30/08/2014
Again the front end user should not give this date period.
I can restrict by using below validation like,
select DocEntry from [#PR_OTIMESHEET] where U_frmdate >='20140801' and U_todate <='20140830'
but user may be give like
from date = 15/08/2014 and to date = 30/08/2014.
In this case above query is become false.
between 01/08/2014 and 30/08/2014 should not give again .
May I know how can I restrict the users ?
The way to query based on a date tends to change based on your database.
For Microsoft SQL Server you need to use CONVERT
Example:
CONVERT(datetime, '20140801', 112)
The 112 is a specified date format. See other date formats here. http://msdn.microsoft.com/en-GB/library/ms187928.aspx
so your example should be:
select DocEntry from [#PR_OTIMESHEET] where U_frmdate >= CONVERT(datetime, '20140801', 112) and U_todate <= CONVERT(datetime, '20140801', 112)
NOTE: Your select range doesn't make any sense as the dates are the same!! So this will only return stuff where the date is exactly 2014-08-01 00:00:00

How Insert DateTime Vales into Mysql Databse ...from the front end application.But User Gives Date only

I am new developer in .net,I Have requirement..like this ,when user pick date from date picker not time only date he/she pick up,then click insert that time ,i want insert that date and time is into Column exist with name "EnterdDate" data type is "DATETIME".
by default 00:00:00 is stored in the Time format I don't want to be stroed that values I want store The at the Time insertion MySql Server Time.
ex:user 12/03/2013 ->insert->click
presently assume server time is 13:00:00
i want insert This Date value --> 2013-03-12 13:00:00 ok for me.
*i don't need the DateAndTime like is :2013-03-12 00:00:00 not Ok for me.*
please give me best answer any body now the above one .
This is for SQL server as you have tagged SQL Server in your question , you can use corresponding Mysql date functions .
Get current time from GETDATE() by
convert(varchar(11),getdate(),108)
this will return a string in format
18:33:03.000
Add this string to selected date and convert the resultant string to DateTime datatype
declare #selectedDate varchar(11)
set #selectedDate = '04/25/2013'
select convert(datetime,#SelectedDate +' ' + convert(varchar(11),getdate(),108))
This returns a datetime value
2013-04-25 18:33:03.000