how to compare a given date with current date in sql - java

i want to write a query to compare a given date with today date with timestamp.
given date can be the today date, if the date is same it will compare the time.
select * from abcTable where submitDate <= now();
here its comparing only the date not the time.
submitDate is anydate which is in the db table.

Firstly, you have specified that column submitDate is of datatype Date while, as per your question its datatype should be Timestamp.When the datatype of submitDate column is Date, there is no reason to even compare the time.
However if you need to still want to compare the submitDate with current timestamp, you can do it this way:
select * from submitDate where date_format(submitDate,'%d/%m/%y %T') <= now();
Edit: The above query is for Mysql

I think you should try:
GETDATE() --2017-01-17 08:19:28.403
you can get day, month and year separately by doing:
select DAY(getdate()) --17
select month(getdate()) --1
select year(getdate()) --2017
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2017-01-17
OR you you can try:
select * from abcTable where submitDate <= CAST(CURRENT_TIMESTAMP AS DATE);
OR
select * from abcTable where submitDate <= cast((now()) as date);

Related

preparedStatement with TimeStamp compare two date

i have this code
preparedStatement = jdbcManager.getConnection().prepareStatement(query);
Date start; /*get from postgres column type-> Timestamp without time zone*/
java.sql.Timestamp timestamp = new java.sql.Timestamp(start.getTime());
log.debug("Parametro d'ingresso query: "+timestamp);
preparedStatement.setTimestamp(1, timestamp);
and i have this query
SELECT
DATA
FROM MY_TABLE
WHERE DATA > ?
the column DATA is DATA_TYPE = DATE in a Oracle db
the compare in the query not working,
what am I doing wrong?
You're comparing date with timestamp. Instead of fetching time stamp, get java.sql.Date. And also in prepared statement, use setDate instead of setTimeStamp.

Sqlite : Comparing timestamp value stored in a column to current Date

I store information in a sqlite database table as follows:
ActionDate column is of type : DEFAULT CURRENT_TIMESTAMP
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I want to write an SQL query that returns all rows in my table having ActionDate value as today's date from sqlite DB. However as ActionDate is of type timestamp what is the most appropriate way to convert it to todays date.
If you want current date then use the following query :
SELECT date('now');
To get all columns in your table having ActionDate equal to todays date use the below query :
select * from table where strftime('%Y-%m-%d ', datetime(ActionDate, 'unixepoch')) = date('now)' ;
more info on SQLite Date & Time queries can be found here

how to insert data type date(yyyy-MM-dd) in sqlite database and retrive data between two dates in android

I have a Sqlite3 database table contains name,address,date of birth details.i want to display 1990-01-01 to 1995-01-01 details.
but Sqlite3 database stores only following data types.
TEXT
NUMERIC
INTEGER
REAL
NONE
Any one have some hint to store and retrieve date format data..?
From my own experience on doing several projects with database in Android my answer is:
Do not store the date as a string. Never! Ever! Store them as Unix timestamps and format them as needed during runtime.
the important thing here is to separate what is your data and what is the on-screen representation of your data. Storing in a database the on-screen representation of your data is wrong.
You'll always store your dates as INTEGER types.
So for example to store the date now you'll store the value System.currentTimeInMilis
To select between 1990-01-01 and 1995-01-01 you will:
long val1 = new GregorianCalendar(1990, 01, 01).getTimeInMillis();
long val2 = new GregorianCalendar(1995, 01, 01).getTimeInMillis();
and then you'll do the normal SELECT statement between those 2 values.
to show those values in the screen as yyyy-MM-dd you'll use the SimpleDateFormat class:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
long longDate = cursor.getLong(colNumber); // from the database
String stringDate = dateFormat.format(new Date(longDate));
Use this code to convert your date into millisecond format and store it into your database as INTEGER types
String someDate = "1995-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(someDate);
System.out.println(date.getTime());
date.getTime()-give the millisecond format
At the same way to convert your input (i.e from 1990-01-01 and to date 1995-01-01)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(1990-01-01);
value1=date.getTime();
Date date2 = sdf.parse(1995-01-01);
value2=date.getTime();
Retrieve from database using following query
db.rawQuery("SELECT * FROM table_name WHERE column_name BETWEEN "+value1+" AND "+value2+"",null);
or
db.rawQuery("SELECT * FROM table_name WHERE column_name<="+value1+" AND column_name>="+value2+"",null);
You can do something like this
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Date date1=df.parse("1990-01-01");
Date date2=df.parse("1995-01-01");
Date myDate=df.parse("1992-01-01"); // checking date
if((date1.getTime()<myDate.getTime())&&(myDate.getTime()<date2.getTime())){
System.out.println(df.format(myDate)+" is in this range");
}else{
System.out.println(df.format(myDate)+" is not in this range");
}
Since the format you want to use (yyyy-MM-dd) is ordered in the same way as a String (i.e. for any dates x and y you would choose, if x < y as a Date, then x < y as a String), you can simply store the dates as Strings (TEXT) in your database.
When selecting the values between them, you would just have to use a WHERE clause in your SELECT statement like this:
SELECT * FROM yourTable WHERE yourDateFieldName > ? and yourDateFieldName < ?
You can then use DateFormat.format to set the values for the ? parameters of your prepared statement. The first parameter would be the "start" date, and the second would be the "end" date. You can replace < with <= and > with >= if you want the items on start and end dates included.
This gives you a String representation of a Date. To convert from that to an actual Date object you can use date formatter's parse method (i.e. SimpleDateFormat.parse).
Another, "cleaner", approach would be to use the SQLite date and time functions (see here). While SQLite doesn't have a DATE type for storing date values, it has helper functions that you can use to interpret TEXT and NUMBER values as date in your statements.
If you don't need extra processing for your date values, I'd recommend going for the first solution as it should be faster because it merely compares TEXTs rather than parsing and extracting a date from them, then comparing the extracted date (I haven't compared the speed of the two approaches, so don't take my word for it on this one). This approach also has less code to write and maintain and the code is easier to read.
Sources:
SQLite data type - for the validity of comparing two TEXT values
SimpleDateFormat - Android documentation
You can use dates in yyyy-MM-dd format directly, JDBC will understand it. Assuming we a have a table t1 with c1 of DATE type
PreparedStatement ps = conn.prepareStatement("insert into t1 (c1) values (?)");
ps.setString(1, "2001-01-01");
ps.executeUpdate();
Reading dates is simple too
ResultSet rs = st.executeQuery("select c1 from t1");
rs.next();
Date date = rs.getDate(1);
ResultSet.getDate returns result as java.sql.Date whose toString method returns date in yyyy-MM-dd format

Date - Java to Sql table and sql table to Java through Joda Time

I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());

insert current time into table

java.util.Date date = new java.util.Date();
java.sql.Date today = new java.sql.Date(date.getTime()); //2012-03-23
java.sql.Time time = new java.sql.Time(date.getTime()); //02:32:46
PreparedStatement pst = null;
String queryString = "INSERT INTO PR_VISITOR(PRISONER_ID,VISITOR_NAME,FATHER_NAME,DOV,IN_TIME) VALUES (?,?,?,?,?)";
pst = connect.prepareStatement(queryString);
pst.setString(1, pr_id);
pst.setString(2, visit);
pst.setString(3, father);
pst.setDate(4, today);
pst.setTime(5, time);
int officerQuery = pst.executeUpdate();
if (officerQuery == 1) {
response.sendRedirect("/FYP3.4/prisonAdmin/visitor_out.jsp");
JOptionPane.showMessageDialog(null, "Visitor information registered !!", "Visitor Information", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Unable to Add information !!", "Visitor Information", JOptionPane.ERROR_MESSAGE);
}
By using the above code i'm trying to insert the current date and time into table,which have the separate columns. When i'm executing the above query then it insert the todays date in the time IN_TIME field too.
EDIT
DATATYPE OF IN_TIME and DOV are DATE .
Need Help.. !!
Since DOV and IN_TIME is date you don't need to separate date and hour. The type date in Oracle holds date and time. I suggest you change your table to have just one date column.
To insert the current time you can use the Oracle's sysdate function:
INSERT INTO PR_VISITOR(PRISONER_ID,VISITOR_NAME,FATHER_NAME,DATETIME_COLUMN) VALUES (?,?,?,?,SYSDATE)
To format your output of the date value you can use the SimpleDateFormat class in Java or to_char in Oracle.
A DATE column in an Oracle database will always store both a day (i.e. March 22, 2012) and a time to the second (i.e. 3:30:00 PM). A java.sql.Date and a java.sql.Time store the day and time as well but to the millisecond.
It doesn't really make sense to have separate columns in Oracle for the day and for the time but particularly not where both columns are declared as DATE data types. It would be much more conventional to use a single column declared as a DATE. If you really wanted to, you could truncate the day so that it represents midnight on the current day and then store the time component as, say, an INTERVAL DAY TO SECOND. But that would generally add a fair amount of complexity to the system for very little gain.
You're much better off using oracle's 'systimestamp'. The reason being, if you're java code is running in one timezone, and oracle lives in another. Forcing your own Time object, could cause problems.
Do you really need separate fields for this? I would think just having a timestamp would be enough.
Use SimpleDateFormat. This is one way I have used it:
Date now = Calendar.getInstance().getTime());
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String date = df.format(now);
DateFormat tf = new SimpleDateFormat("HHmmss");
String time = tf.format(now);
Follow this,it will help both in java and oracle
create table datetime(date_time timestamp);
insert into datetime values (sysdate);
To get date:
select to_char(date_time,'DD-MON-YY') from datetime;
eg:12-JUL-12
To get month:
select to_char(date_time,'mm') from datetime;
eg:7
To get time:
select to_char(date_time,'HH24:MI:SS') from datetime;
eg:23:56:15
cheers!!

Categories