How to fix NumberFormatException? - java

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String selectQueryForPatient = "SELECT registration_id, dob FROM patient_registration WHERE registration_id IN(SELECT max(registration_id)FROM patient_registration)";
String insertQuery = "INSERT INTO patient_master_info(patient_id) VALUES (?);";
String id = null;
String dob = null;
int generatedID = 0;
try {
pst = con.prepareStatement(selectQueryForPatient);
rs = pst.executeQuery();
while(rs.next()){
id = Integer.toString(rs.getInt(1));
dob = rs.getString(2);
System.out.println("Id : "+id+" "+"DOB: "+dob);
Date dt = sdf.parse(dob);
dob = sdf.format(dt);
String result = id.concat(dob);
generatedID = Integer.parseInt(result);
}
pst = con.prepareStatement(insertQuery);
pst.setInt(1, generatedID);
pst.execute();
} catch(Exception e) {
e.printStackTrace();
}
For input string: "12919851203" I got java.lang.NumberFormatExceptionexception. How do I fix it?
`

I don't know what you are trying to do, but your problem is that the result of appending a date to an integer value easily exceeds the integer range.
For example, let id be "30" and dob (as read from the database) be "20190123". The result of id.concat(dob) is "3020190123", which is larger than "2147483647", the maximum value for an int.
Your sample value 12919851203 is even much larger (almost 13 billion, while Integer.MAX_VALUE is about 2 billion).
If the value has to be sortable like numbers (where 2 < 10) then you could change the datatype to long or BigInteger.
If the sorting doesn't matter (i.e. it's OK that "2" is larger than "10") then you could even store result as String (into a VARCHAR column).
Or you could explain what problem you want to solve so that we could find a better way to solve the problem.

This answer is not about the number format exception but about the date format mistake you have made.
For the moment, you are parsing 1986-03-01 into the date 1985-12-03 because your String dob contains -. You need two distinct formaters to get your result:
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyyMMdd");
String dob = "1985-03-01";
Date dt = sdfIn.parse(dob);
dob = sdfOut.format(dt);
System.out.println(dob);
19850301
Of course, one could argue about the need to parse into a Date just to get a "similar" String, if you are sure about your data being a date, you can just remove - using :
dob = dob.replaceAll("-", "");
Last thing, you should use java.time API.
String dob = "1985-03-01";
LocalDate date = LocalDate.parse(dob, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
dob = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
System.out.println(date);
System.out.println(dob);

Related

Date cannot be updated in jdbc(Using Prepared Statement)

So my problem is that I want to allow the user to change the shipping date of the product according to what they want. So what I did is that I collect the year,month and day input from the user and convert it into the date format that SQL required. All the input was fine but whenever I wanted to update the shipping date, it doesn't update and neither shows the error.
I used the input that I got from the user to set the Calendar class's year,month and date. Then I converted the date into the java.util.Date before I could convert it into java.sql.Date
//sql query
private static final String UPDATESHIPPINGDATE = "UPDATE book SET shippingDate = ? WHERE orderID = ? ";
//Required format for SQL
private static final String DATE_FORMAT_NOW = "yyyy-MM-dd";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
//The method
public void updateShippingDate(int orderID, int year,int month,int day){
try(Connection con = DBConnection.getConnection();
PreparedStatement stmtUpdate = con.prepareStatement(UPDATESHIPPINGDATE);
PreparedStatement stmtShippingDate = con.prepareStatement(GETSHIPPGINGDATE);
){
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,(month-1));
cal.set(Calendar.DATE,(day-1));
Date dateConvert = cal.getTime();
java.sql.Date shippingDate = new java.sql.Date(dateConvert.getTime());
stmtUpdate.setInt(1,orderID);
stmtUpdate.setDate(2,shippingDate);
stmtUpdate.executeUpdate();
stmtShippingDate.setInt(1,orderID);
ResultSet result = stmtShippingDate.executeQuery();
while (result.next()){
System.out.println("Your new shipping date: " + result.getDate("shippingDate"));
}
}catch (Exception e){
System.out.println(e);
}
}
Expected: 2019-06-20(updated output)
The output was: 2019-06-24(old output)

UpdateQuery doesn't execute. How to fix this code?

I want to get the date in DATE column and want to compare with the current date. if the date is less than current date then I want to SET the value of PERMISSION column allow. But my Query doesn't execute.
Which I have tried is given in my below code.
Date date1 = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//current date
Date date = new Date();
date1 = date;
CurrentDate.setText(date1.toString());
String UpdateQuery = null;
String Allow = "allow";
UpdateQuery = "UPDATE company SET permission = '"+Allow+"' WHERE date < ?";
pst = conn.prepareStatement(UpdateQuery);
SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd");
String addDate = CurrentDate.getText();
pst.setString(2, addDate);
pst.executeUpdate();
System.out.println("Updated");
I want to get a value of permission table to SET to "allow" when the update query is executing;
pst.setString(2, addDate);
I think this should be changed to:
pst.setString(1, addDate);
because you only have one parameter in your prepared statement.
Also, when comparing dates, you need to enclose them in single quotes, so changing your UpdateQuery string to
"UPDATE company SET permission = '"+Allow+"' WHERE date < '?' ";
is also a necessary step.

Java JDBC how to pass date in

How can I take the the date value from my html, then add it to the database.
I tried many ways but its not working. I keep getting back a NULL value in the database or an error message "java.text.dateformat.parse(unknown source)"
HTML:
Date Of Birth: <input type="date" name="dob">
JAVA:
String date = request.getParameter("dob");
Date dob1 = new SimpleDateFormat("MM/dd/yyyy"));
PreparedStatement createUser = connection.prepareStatement(
"INSERT into users (dob1)" +
" VALUES ( ?)");{
createUser.setDate(1, (java.sql.Date) dob1);
int newUser = createUser.executeUpdate();
}
String date = request.getParameter("dob");
Date dob1 = new SimpleDateFormat("MM/dd/yyyy"));
This second line is wrong. Change to
Date dob1 = new SimpleDateFormat("MM/dd/yyyy")).parse(date);
edit
By the comment you're using the wrong date format. Use it instead.
Date dob1 = new SimpleDateFormat("yyyy-MM-dd")).parse(date);

Date filtering using JDBC

What is the correct format for date filtering - JDBC to SQL
I have been trying to use the following with an MS-Access DB
SELECT doctorbusiness.dateofreport,
doctorbusiness.patientname,
doctorbusiness.labcomm,
doctorbusiness.xcomm,
doctorbusiness.spccomm,
doctorbusiness.ecgcomm
FROM doctorbusiness
WHERE doctorbusiness.doctorname = '"+selectedDoc+"'
AND (( doctorbusiness.dateofreport >= # "+sd+" # )
AND ( doctorbusiness.dateofreport <= # "+ed+" # ))
selectedDoc is in String and sD and eD in date format.
The query runs fine in MS-Access but gives the following exception :
net.ucanaccess.jdbc.UcanaccessSQLException: unknown token:
UPDATE
public void printDoctorIncome() {
Date startDate = easypath.docB_startDate_jxdp.getDate();
Calendar calSD = Calendar.getInstance();
calSD.setTime(startDate); // convert your date to Calendar object
int daysToDecrement = -1;
calSD.add(Calendar.DATE, daysToDecrement);
Date real_StartDate = calSD.getTime();
SimpleDateFormat sdF1 = new SimpleDateFormat("dd-MM-yyyy");
String sD = sdF1.format(real_StartDate);
JOptionPane.showMessageDialog(null, sD);
Date endDate = easypath.docB_endDate_jxdp.getDate();
Calendar calED = Calendar.getInstance();
calED.setTime(endDate); // convert your date to Calendar object
int daysToIncrement = +1;
calED.add(Calendar.DATE, daysToIncrement);
Date real_endDate = calED.getTime();
SimpleDateFormat sdF2 = new SimpleDateFormat("dd-MM-yyyy");
String eD = sdF2.format(real_endDate);
JOptionPane.showMessageDialog(null, eD);
String selectedDoc = easypath.drname_jlist.getSelectedValue().toString();
String sql = "SELECT doctorBusiness.dateofreport, doctorBusiness.patientName, doctorBusiness.labComm, doctorBusiness.xComm, doctorBusiness.spcComm, doctorBusiness.ecgComm FROM doctorBusiness WHERE doctorBusiness.doctorname ='"+selectedDoc+"' AND (doctorBusiness.dateofreport >= ?"+sD+"? AND doctorBusiness.dateofreport <= ?"+eD+"?)";
try {
conn = connectDB.getConnection();
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
doctorIncome.docIncomePrint_table.setModel(DbUtils.resultSetToTableModel(rs));
doctorIncome dI = new doctorIncome();
dI.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
}
This is the code I am using
With JDBC better way to do it is use setDate/Time/Timestamp methods of PreparedStatement. And you shouldn't care about concrete DB's date format.
Date dateFrom = ...
Date dateTo = ...
String sql = "... where myDate >= ? and myDate <= ? "
preparedStatement.setDate(1, dateFrom);
preparedStatement.setDate(2, dateTo);
Using a PreparedStatement is a good idea. But you can also use either #MM/dd/yyyy# or #yyyy-MM-dd# (with or without hours:minutes:seconds).

timestamp to date in java and get the count value

hi i have to convert timestamp to date after check the query and return the count value.
my database have date(1344399208,1344399269),status(Q,Q).
This is my code:
public class GetCurrentDateTime {
public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while(result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return count;
}
}
Here the date is saved in timestamp format.but i like to convert date(yyyy-mm-dd) format.its done successfully.ya i got the output is 2012-08-08.but i have to check the query today date+status=Q .so how is that date is save in variable and call that variable in query.so how is wrote query for above condition.after check the condition and display the returns count value on my tomcat console.How is to do.please help me
Partial Answer to your Question
Date Examples
Examples borrowed from Code Ranch and SO posts
// Get system time
Timestamp SysTime = new Timestamp(System.currentTimeMillis());
java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());
// Date + Time + Nano Sec
System.out.println(SysTime);
// Date + Time
System.out.println(UtilDate);
// Date
System.out.println(SQLDate);
Formatting Dates
// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);
Please note that I am new to java, hence verify if it works.
Comparing dates
See this SO post:
How to compare dates using Java
To convert date to the date format specified:
int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format
From what I understand from the edit, you want the query to be something like this:
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");
I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.
From comments:
To get midnight date:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
To get all entries within a 24 period:
"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);

Categories

Resources