how to check linq comparing date format in vb.net - 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)

Related

Date format value not updating from previous format to new format after update

When I update a column from a table with a date format of MMM DD,YYYY to a new format. The format doesn't change to the desired format which is YYYY-MM-DD HH:MM:SS. Even when update different value like GETDATE(). The date will change but the format will remain the same.
Current value & format from column the type is varchar
DueDate
Jun 27 2020 12:00AM
Desired format
DueDate
2020-06-27 00:00:00.000
Update statement
update TableName
set
DueDate = CAST([DueDate] AS smalldatetime),
LastSyncDateTime = GETDATE()
where CaseGuid = 'DA2CE6A1-0394-463E-8E8D-962F3A24ADC8'
There is a huge confusion between "Date displaying format" and "Date storing format". The VERY short explanation is that what you mentioned is only a client side displaying format, while SQL Server have specific format which is used for storing dates (remember that the server stores zero and one only).
You can insert dates to a table using different styles (the official name for the displaying format is STYLE), and you can present the dates in the client side using different style, but it will always be stored the same from the "SQL Server point of view" according to the DATE type which is used.
In order to solve your original needs, all that you needed to do is to provide the server the information about the style which you use in the client side (in the query). This is done by using explicit CONVERT with the third parameter, which is the STYLE.
For example if you use in the client side an Israeli format like dd/MM/yyyy, then you should use CONVERT(DATE, '27/02/2021', 103).
For more information on different STYLEs you can check this documentation.
Note: If you want to display the dates in specific format which is not covered by the existing STYLEs then you can use the function FORMAT() in your query. This function is fully flexible to return the data in your specific format. Remember that this function returns the data as string and it will not be date anymore.
For example, let's say that I want to use the format: "Day:dd,Month:MM,Year:yyyy". So if the date is '27/02/2021' then I expect to get "Day:27,Month:02,Year:2021". In this case use below:
DECLARE #D DATE
SET #D = CONVERT(DATE, '27/02/2021', 103) -- convert string to date for storing
select FORMAT(#D, 'Day:dd, Month:MM, Year:yyyy') -- convert date to string for displaying
Solution use the format function
update TableName
set
DueDate = FORMAT (CAST([DueDate] AS smalldatetime),'yyyy-MM-dd HH:mm:ss'),
LastSyncDateTime = GETDATE()
where CaseGuid = 'DA2CE6A1-0394-463E-8E8D-962F3A24ADC8'
https://www.sqlshack.com/a-comprehensive-guide-to-the-sql-format-function/

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

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)

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 =?;

Comparing a date and getting result of records having further dates

I am using sql for database connectivity. I am filtering records in database on date basis using sql query which consists of function convert(varchar(100),column name,106). I am comparing it with date having dd/MMM/yyyy format. As a result I get records of next all the dates.
Example: If I try to filter the table by 01/June/2017 then inspite of having records of that date, I get records of next all the dates. I am not able to get records of 01/June/2017.
I have used greater than or equal to expression.
It is better to convert it to this yyyymmdd number format and do the comparison as below:
select convert(int,convert(varchar(10),[your column],112))
20170529
Don't convert your dates into any format (=strings) when doing comparison. Always use the date (or datetime etc) format. That way you will be comparing the actual values, not string or numeric comparison. Here the problem is that format 106 is dd mon yyyy so it will never match your date because it's a string dd/MMM/yyyy but you will get any dates starting with 02 anyhow, for example 02/Jan/1990, because in alphabetical order that will come after your given date.

Date range comparison using varchar columns in Teradata

I've been tasked to take a calendar date range value from a form front-end and use it to, among other things, feed a query in a Teradata table that does not have a datetime column. Instead the date is aggregated from two varchar columns: one for year (CY = current year, LY = last year, LY-1, etc), and one for the date with format MonDD (like Jan13, Dec08, etc).
I'm using Coldfusion for the form and result page, so I have the ability to dynamically create the query, but I can't think of a good way to do it for all possible cases. Any ideas? Even year differences aside, I can't think of anything outside of a direct comparison on each day in the range with a potential ton of separate OR statements in the query. I'm light on SQL knowledge - maybe there's a better way to script it in the SQL itself using some sort of conversion on the two varchar columns to form an actual date range where date comparisons could then be made?
Here is some SQL that will take the VARCHAR date value and perform some basic manipulations on it to get you started:
SELECT CAST(CAST('Jan18'||TRIM(EXTRACT(YEAR FROM CURRENT_DATE)) AS CHAR(9)) AS DATE FORMAT 'MMMDDYYYY') AS BaseDate_
, CASE WHEN Col1 = 'CY'
THEN BaseDate_
WHEN Col1 = 'LY'
THEN ADD_MONTHS(BaseDate_, -12)
WHEN Col1 = 'LY-1'
THEN ADD_MONTHS(BaseDate_, -24)
ELSE BaseDate_
END AS DateModified_
FROM {MyDB}.{MyTable};
The EXTRACT() function allows you to take apart a DATE, TIME, or TIMESTAMP value.
You have you use TRIM() around the EXTRACT to get rid of the whitespace that is added converting the DATEPART to a CHAR data type. Teradata is funny with dates and often requires a double CAST() to get things sorted out.
The CASE statement simply takes the encoded values you suggested will be used and uses the ADD_MONTHS() function to manipulate the date. Dates are INTEGER in Teradata so you can also add INTEGER values to them to move the date by a whole day. Unlike Oracle, you can't add fractional values to manipulate the TIME portion of a TIMESTAMP. DATE != TIMESTAMP in Teradata.
Rob gave you an sql approach. Alternatively you can use ColdFusion to generate values for the columns you have. Something like this might work.
sampleDate = CreateDate(2010,4,12); // this simulates user input
if (year(sampleDate) is year(now())
col1Value = 'CY';
else if (year(now()) - year(sampleDate) is 1)
col1Value = 'LY'
else
col1Value = 'LY-' & DateDiff("yyyy", sampleDate, now());
col2Value = DateFormat(sampleDate, 'mmmdd');
Then you send col1Value and col2Value to your query as parameters.