I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement
Related
I have a HTML form inside which i have a Date-picker which is only for month and Year, so user is selecting month and year then submitting the form so at my server end i.e Java Servlet i am getting that value by request.getParameter
and it is giving 08/2018 08 is the month and 2018 is year
so in my server end i have to write a query which can give me the data of the month-year which is selected
query i am thinking of is something like this
select cashier from tableName where billdate=''
so what value should i give to bill date so that it gives me data for the selected month like currently i have month as 08 and year as 2018
Note:- i am using MySql5.5
EDIT
As i can use this query also :- SELECT * FROM tableName WHERE YEAR(billdate) = 2018 AND MONTH(billdate) = 8
but the issue is i am getting date as 08/2019 how can i split it into two variables
You are getting date as 08/2019. Then to split it into month and year, you can use String function split(). For example,
String monthYear = "08/2019";
String[] arr = monthYear.split("/");
String month = arr[0]; //08
String year = arr[1]; //2019
One way is to use string.split:
String date = "08/2019";
String[] components = date.split("/");
String month = components[0];
String year = components[1];
If you have the day as well, you could parse a LocalDate from it:
String fullDate = "01/08/2019";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uuuu");
LocalDate localDate = LocalDate.parse(fullDate, formatter);
localDate.getYear();
localDate.getMonth();
I have an SQL table in my Android project, that has a KEY_DATE field in Date format.
KEY_DATE + " DATE,"
My table is populated from the java code (date in dd/mm/yy format).
So now I need to make several date-related queries and something isn't working.
I need to make selections from a table for today, this month and this year.
Here's what I tried:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
Date todayD = new Date();
dateFormat.format(todayD);
String today = dateFormat.format(todayD);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
dateFormat.format(firstDay);
String selectQuery = "SELECT * FROM " + TABLE_PAYMENTS + "WHERE "
+ KEY_DATE +" BETWEEN " + firstDay + " AND " + today;
The query returns empty even though there's a lot of data for that period.
I believe something is wrong with data formats here. Can you help me to solve this?
Thank you in advance.
You are not formatting firstD, so you only get from the first day of the month at the current time on;
You should either use single quotes around the dates in your queries or use prepared statements, otherwise your server will understand your dates as math operations;
When querying for date ranges, remember that if you don't specify an hour with your date SQL will by default take it as zero hour (0:00:00.0000). If you use "between startDate and today", you get only midnight of today. If you use "between startDate and tomorrow", you get midnight of tomorrow too. You should use "date >= startDate and date < tomorrow" to get the proper range.
When writing queries with dates, I always prefer to use ISO format for the date strings: yyyy-MM-dd.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date todayD = new Date();
cal.setTime(todayD);
cal.add(Calendar.DATE, 1);
Date tomorrowD = cal.getTime();
String today = dateFormat.format(tomorrowD);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstD = cal.getTime();
String firstDay = dateFormat.format(firstD);
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE KEY_DATE >= '" + firstDay + "' AND KEY_DATE < '" + today + "'";
The problem is with the date formats for the data present inside the database and the date formats that you are passing (strings) to the sql query.
It is not a good practice to pass dates as string parameters to the sql query, so I strongly suggest use preparedStatement as shown below:
Date todayD = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE BETWEEN ? AND ?" ;
//create preparedStatement here
preparedStatement.setDate(1, firstDay);
preparedStatement.setDate(2, todayD);
I am trying to create a date object(format : HH:MM) from a String Example 13:30(HH:MM). I want to save the HH:MM in MySql table but the below code enters some random value in the column (eg: '6828-00-00 00:00:00'). How can i store the date value in Mysql in the HH:MM format ?
Date date = null;
String afternoon = "13" +":" +"30";
String time = afternoon;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
e.printStackTrace();
}
long d = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(d);
String sql3 = "CREATE TABLE IF NOT EXISTS DateTime"+
"(UniqueBusID VARCHAR(255) not NULL, " +
" Timenings DATETIME DEFAULT NULL ,"+
" PRIMARY KEY ( UniqueBusID ))";
stmt.executeUpdate(sql3);
stmt.executeUpdate("INSERT INTO DateTime " + "VALUES ('Test3','"+sqlDate.getTime()+"')");
EDIT
You have to use java.sql.Timestamp instead of java.sql.Date. As from javadoc,
"To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated."
So just replace the line
java.sql.Date sqlDate = new java.sql.Date(d);
with
java.sql.Timestamp sqlTime = new Timestamp(d);
You are doing it all right, except the pattern you have used to parse the String as Date i.e. HH:mm, which is wrong.
Correct Format : H:mm (H: 0-23; h:1-12)
try {
date = new SimpleDateFormat("H:mm").parse(time);
}
Here is the reference for Date and Time Patterns
I am surprised that it inserted '6828-00-00 00:00:00' :-)
Four problems here.
[1]
First that when you set a SimpleDateFormat, you're creating a java object Date. Java Date starts from Jan 1st 1970, so if you set only the hour and minute, the formatter will assume all other fields are zero (and not today), so
System.out.println(new SimpleDateFormat("HH:mm").parse("13:30")); // returns Thu Jan 01 13:30:00 BRT 1970
[2]
But then, you've called the getTime() method, which returns the millis since Jan 1st 1970
System.out.println(new SimpleDateFormat("HH:mm").parse("13:30").getTime()); //59400000
[3]
Then, you've tried to push this number into MySQL. MySQL datetime expects a string in the format
YYYY-MM-DD HH:MM:SS
(see https://dev.mysql.com/doc/refman/5.0/en/datetime.html)
Since MySQL is a very benevolent database ;-) it tries to convert 59400000 into this format, which obviously
mysql> insert into d values (59400000);
Query OK, 1 row affected (0.04 sec)
mysql> select * from d;
+---------------------+
| y |
+---------------------+
| 5940-00-00 00:00:00 |
+---------------------+
1 row in set (0.08 sec)
[4]
Of course, you could just adjust your SimpleDateFormat to MySQL expected date format, but you're concatenating strings in a INSERT query, and this is not a good idea for security reasons neither is efficient. Instead, you should use a PreparedStatement and set the Date object (not the millis)
To store a Calendar object in SQLite database, i found that the easiest way is to convert the Calendar object to a string and store it in the database as text.
Now, the problem lies in extracting the stored date from the string.
How do I parse the string containing the Calendar object and set it to a Calendar value?
My code is:
String CREATE_DOCTORS_TABLE = "CREATE TABLE " + TABLE_DOCTORS + "("
+ KEY_ID_DOC + " INTEGER PRIMARY KEY," + KEY_DOCTOR_NAME + " TEXT,"
+ KEY_CLINIC_ADDRESS + " TEXT," + KEY_LAST_CHECKUP + " TEXT" + ");";
db.execSQL(CREATE_DOCTORS_TABLE);
where KEY_LAST_CHECKUP contains a value like this:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=4,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=198,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=47,MILLISECOND=823,ZONE_OFFSET=19800000,DST_OFFSET=0]
and i've stored it in a database this way:
values.put(KEY_LAST_CHECKUP, (doctor.getLastCheckUpDate().toString())); // last check up date
Now, how do i retrieve the DAY, MONTH and YEAR from the stored string?
I read about how to convert a date string to a calendar object here:
How to convert a date String to a Date or Calendar object?
but my string is not just a date string. It contains a lot of other details too.
What is the best way forward?
Change your data model to use a Date. This is the usual type to be stored in the database.
You can set the Date to a Calendar by using
Calendar c = Calendar.getInstance();
c.setTime(date);
To retrieve the Date from a Calendar you can use
date = c.getTime();
Using a String to store a Date in a database needs formatting and parsing of the Strings and also no comparision iside the database can be done.
If you would like to keep string value in KEY_LAST_CHECKUP column. Try to use SimpleDateFormat.
If you keep long value, you don't need to use SimpleDateFormat.
For insert :
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strDate = simpleFormat.format(doctor.getLastCheckUpDate());
values.put(KEY_LAST_CHECKUP, strDate);
For retrieve:
try {
String strDate = --> from DB
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(strDate);
Calendar c = Calendar.getInstance();
c.setTime(parsedDate);
} catch (ParseException e) {
return "Unknown";
}
I am trying to insert a dd/mm/yyyy date format into my database table. The data type for date column in database is date and my SQL insert statement is:
INSERT INTO sm_product(productName, productDescription, productPrice, productQuantity, productStatus)
VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ", 'Available', '" + date + "'";
However, netbeans shows me an error when I added the date variable into the SQL statement.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
And it stores the date as:
Wed Jun 19 17:42:26 SGT 2013
And I got my dd/mm/yyyy date format in user interface:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
dateFormat.format(date);
This format is not I wanted. So I wonder how should I amend my SQL statement to fix the problem.
Thanks in advance.
If you are using SQL Server , you can use
REPLACE(CONVERT(VARCHAR(11),date,105),'-','/')
If you insert following format sting into query, record will be updated
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String formatDate = dateFormat.format(date);