java.sql.SQLException: ORA-01843: not a valid month error - date format conversion issue - sql

I'm having a strange issue here with a query from which I'm trying to pull data queried by start and end date parameters.
I'm conducting the following.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String preparedQuery = "SELECT ID, FULNAME, FRMEMAIL, LOCATION,TYPE1,TYPE2,BORROWER_NAME,LOAN_NUM,TIME_REQ
FROM FORM_REDUCVU WHERE to_date(TIME_REQ,'yyyy-mm-dd') >= ? AND to_date (TIME_REQ,'yyyy-mm-dd') <= ? ORDER BY ID DESC";
java.util.Date util_StartDate = sdf.parse( request.getParameter("time_req_date") );
java.sql.Date timreq_datevar1 = new java.sql.Date( util_StartDate.getTime() );
java.util.Date util_EndDate = sdf.parse( request.getParameter("time_req_date2") );
java.sql.Date timreq_datevar2 = new java.sql.Date( util_EndDate.getTime() );
out.println("datestamp java time vals "+timreq_datevar1 + " " + timreq_datevar2);
PreparedStatement prepstmt = connection.prepareStatement(preparedQuery);
prepstmt.setDate(1, timreq_datevar1);
prepstmt.setDate(2, timreq_datevar2);
And the out.print values will give something like 2018-10-09 and 2019-02-20.
This does match the date picker selections I'm making, which are in mm/dd/yyyy format, i.e. 10/09/2018 and 02/20/2019.
Now the above returns no errors in the log, but no data either. But I did have the SQL query as "
WHERE to_datechar(TIME_REQ,'mm/dd/yyyy') >= ? AND to_char(TIME_REQ,'mm/dd/yyyy') <= ?
When changing to this above, I get the error in the topic of not a valid month.
I would have thought the SimpleDateFormat class would have parsed the date to mm/dd/yyyy in pattern, but it seems to make the java.slq.Date object pattern hyphenated, like yyyy-mm-dd.
Am I not parsing it correctly? Or is this going to require a different class or package, like java.Time? I would thought this would work, but there has to be some small conversion method not working.
Bottom line - I'd really prefer to keep the jQuery date pickers with their mm/dd/yyyy formats in tact, and be able to query by these entries.
Any input regarding this is welcomed.
Thank you!

Do NOT use to_date() on a column that is alread a DATE to_date() will convert the date to a varchar just to convert it back to a DATE which it was to begin with.
So your condition should be:
WHERE TIME_REQ >= ? AND TIME_REQ <= ?
You are correctly using setDate() so Oracle performs a date to date comparison - there is no need to convert the date in the database to a string value.
Ideally you should use java.time.LocalDate and setObject() instead of java.sql.Date though (however not all Oracle driver versions support that)

Related

Compare Dates in Kotlin

How can i compare Dates in Kotlin?
I have the Date of an Event as a String (Format:dd/mm/yy) and I want to check if it is within the next 7 Days of the current Date.
The time in this case is not relevant or if needet I would use midnight.
Can someone please help me with this?
In my current code i got both Dates by this:
val date = document.data["Date"].toString() //Example: 22/08/22 (dd/MM/yy)
val today = SimpleDateFormat("dd/MM/yy").format(Date()).toString()
this is within a Android environment.
I can't get the date more specific because i am getting it from a Database.
Parse string into LocalDate using its parse method. There’s no out-of-the-box DateTimeFormatter for dd/mm/yy format, but you can trivially create one using DateTimeFormatter.ofPattern.
Get current date using LocalDate.now().
diff = ChronoUnit.DAYS.between(now, date1)

sql teradata filtering on date - database version Teradata 15.10.06.02 and provider version Teradata.Net 15.11.0.0

my table has a date column. its data type is date. I confirmed it by going to table name>>columns and it says MTH_END_DT [DATE, Not NULL]
I want to filter my data for a particular date. If I put a condition where MTH_END_DT = '6/1/2018' I get an error select failed [3535] A character string failed conversion to a numeric value.
I followed this page. I used where MTH_END_DT = date '6/1/2018' and i get an error syntax error invalid date literal
I tried where cast(timestamp_column as date) = date '2013-10-22'; something like this and it throws error too
How should i filter my data?
There's only one reliable way to write a date, using a date literal, date 'yyyy-mm-dd'
where MTH_END_DT = DATE '2018-06-01'
For a Timestamp it's
TIMESTAMP '2018-06-01 15:34:56'
and for Time
TIME '15:34:56'
In SQL Assistant it's recommended to switch to Standard SQL format YYYY-MM-DD in Tools-Options-Data Format-Display dates in this format
I did have the similar problem when I was filtering a particular date for my query with Teradata. First method I tried was putting 'DATE' term as the following:
WHERE saledate = DATE'04/08/01' but this did not solve the problem.
I then used an approach I stumbled upon when surfing, finally it worked.
WHERE extract(year from saledate)=2004 AND extract(MONTH from saledate)=8 AND extract(DAY from saledate)= 1 source
I think this really should not be this long, but it worked.
It seems to me it’s most likely you have input the date format incorrectly? Maybe it includes a time by default.
For example
where MTH_END_DT = ‘2013-10-22-00:00:00:00’

DB2 Convert Number to Date

For some reason (I have no control over this) dates are stored as Integers in an iSeries AS400 DB2 system that I need to query. E.g. today will be stored as:
20,171,221
Being in the UK I need it to be like the below in Date format:
21/12/2017
This is from my query: (OAORDT = date field)
Select
Date(SUBSTR( CHAR( OAORDT ),7,2) ||'/' || SUBSTR(CHAR ( OAORDT ),5,2) || '/' || SUBSTR(CHAR (OAORDT ),1,4)) AS "Order Date"
from some.table
However, all I get is Nulls. If I remove the Date function, then it does work but its now a string, which I don't want:
Select
SUBSTR( CHAR( OAORDT ),7,2) ||'/' || SUBSTR(CHAR ( OAORDT ),5,2) || '/' || SUBSTR(CHAR (OAORDT ),1,4) AS "Order Date"
from some.table
How do I convert the OAORDT field to Date?
Just to update - I will be querying this from MS SQL Server using an OpenQuery
Thanks.
1) How do I convert the OAORDT field to Date?
Simplest is to use TIMESTAMP_FORMAT :
SELECT DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD'))
2) Being in the UK I need it to be [...] in Date format 21/12/2017 :
SELECT VARCHAR_FORMAT(DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD')),'DD/MM/YYYY')
Note, you didn't specify where you are doing this, but since you tagged as ibm-midrange, I am answering for embedded SQL. If you want JDBC, or ODBC, or interactive SQL, the concept is similar, just the means of achieving it is different.
Make sure SQL is using dates in the correct format, it defaults to *ISO. For you it should be *EUR. In RPG, you can do it this way:
exec sql set option *datfmt = *EUR;
Make sure that set option is the first SQL statement in your program, I generally put it immediately between D and C specs.
Note that this is not an optimal solution for a program. Best practice is to set the RPG and SQL date formats both to *ISO. I like to do that explicitly. RPG date format is set by
ctl-opt DatFmt(*ISO);
SQL date format is set by
exec sql set option *datfmt = *ISO;
Now all internal dates are processed in *ISO format, and have no year range limitation (year can be 0001 - 9999). And you can display or print in any format you please. Likewise, you can receive input in any format you please.
Edit Dates are a unique beast. Not every language, nor OS knows how to handle them. If you are looking for a Date value, the only format you need to specify is the format of the string you are converting to a Date. You don't need to (can't) specify the internal format of the Date field, and the external format of a Date field can be mostly anything you want, and different each time you use it. So when you use TIMESTAMP_FORMAT() as #Stavr00 mentioned:
DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD'))
The format provided is not the format of the Date field, but the format of the data being converted to a Timestamp. Then the Date() function converts the Timestamp value into a Date value. At this point format doesn't matter because regardless of which external format you have specified by *DATFMT, the timestamp is in the internal timestamp format, and the date value is in the internal date format. The next time the format matters is when you present the Date value to a user as a string or number. At that point the format can be set to *ISO, *EUR, *USA, *JIS, *YMD, *MDY, *DMY, or *JUL, and in some cases *LONGJUL and the *Cxxx formats are available.
Since none of variants suited my needs I've came out with my own.
It is as simple as:
select * from yourschema.yourtable where yourdate = int(CURRENT DATE - 1 days) - 19000000;
This days thing is leap year-aware and suits most needs fine.
Same way days can be turned to months or years.
No need for heavy artillery like VARCHAR_FORMAT/TIMESTAMP_FORMAT.
Below worked for me:
select date(substring(trim(DateCharCol), 1, 2)||'/'||substring(trim(DateCharCol), 3, 2)||'/'||'20'||substring(trim(DateCharCol), 5, 2)) from yourTable where TableCol =?;

soapui jdbc: java.sql.SQLException: Data type mismatch. (2015-02-04)

I need to use sql query to DB from soap every day automatically.
Query to DB has current date.
So, I do following:
1) I set current date to properties with groovy:
def dateTime= new Date()
setProperty.setPropertyValue('currDate', String.format("%tF", dateTime, new Date()))
2) in jdbc request I make corresponding property, and try to use it in query:
select * ...
where SENDDATE = :Date
But trying to execute query leads to mismatching of datatypes.
2015-02-04 17:17:54 - Error getting response; java.sql.SQLException: Data type mismatch. (2015-02-04)
So, my question is: how to avoid mismatching in this case?
Note: query is working correct with '2015-02-02' direct filled date.
Dmitry
You could use SQL to figure out the date, and then it will always be in the correct format:
select * ...
where SENDDATE = now()
First of all, make sure your mysql field data type is relevant (it should be 'date' not time(), text, varchar etc.)
Regarding the groovy formatting way, Here is how:
import groovy.time.*
def dateTime= new Date().format('yyyy/MM/dd')
testRunner.testCase.testSteps["Properties"].setPropertyValue('currDate',dateTime.toString())
JDBC (mysql Engine) Query:
select * ...
where SENDDATE = '${Properties#currDate}'
Notes:
The format in your db will be standard like 2015-02-05
You can have the format like 'yyyy/MM/dd HH:mm:ss' if you want to have the time as well, in that case you mysql field datatype must be 'datetime()'.
As #SiKing suggest you can use SQL functions, only note that if you're using an sqlserver instead of now() you've to use GETDATE():
select * ...
where SENDDATE = GETDATE()
Anyway if you want to use your parameter instead of the functions and sometimes seems that string doesn't work as date you can try to convert the string to date using format functions, since it's not clear to me what DB are you using I show you the follow cases:
oracle
select * ...
where SENDDATE = TO_DATE(:Date, 'yyyy-mm-dd')
mySql
select * ...
where SENDDATE = STR_TO_DATE(:Date, '%Y-%m-%d')
sqlserver
select * ...
where SENDDATE = CONVERT(DATETIME,:Date,20)
The sqlserver case is the less intuitive, 20 is the format for yyyy-mm-dd hh:mi:ss so I'm not really sure that you can convert 2015-02-04 maybe you've to append hh:mi:ss in your groovy as 2015-02-04 00:00:00
Hope this helps,

how to check linq comparing date format in vb.net

Say I want record of all employees of date "07/03/2013" where format is "MM/dd/yyyy".
my expression in linq will be :
_dbContext.EmployeeDetails.Where(Function(f) f.EmpId = _empId And f.Date="07/03/2013")
here how linq manage the date format as "MM/dd/yyyy". OR how to compare "f.Date" with MM/dd/yyyy ?
Say,
if i does
_dbContext.EmployeeDetails.Where(Function(f) f.EmpId = _empId And f.Date.ToString("MM/dd/yyyy")="07/03/2013")
It does not allow me. suppose my date will "07/13/2013" then we can consider it matches and sync the format with "f.Date" but what about date is under 12 ? In fact by using first expression, m getting march month records, rather July.
How to figure out this issue?
You are comparing string representations of the date/time, which depend on the current system's formatting options. Use a date literal (must be in 'M/d/yyyy') to create a new DateTime object:
_dbContext.EmployeeDetails.Where(Function(f) f.EmpId = _empId And f.Date=#3/7/2013#)
If it's a variable, say dte:
_dbContext.EmployeeDetails.Where(Function(f) f.EmpId = _empId And f.Date=dte)
It should be this:
_dbContext.EmployeeDetails.Where
(Function(f) f.EmpId = _empId And
f.Date.ToString("dd/MM/yyyy")="07/03/2013")
You where passing Month first, so it parses March. Change toString order so you pass days before and then month. (July)