the error occur near the parsing of proj_close_date.( java.text.ParseException: Unparseable date: "09/09/2010" )
i am reading project_close_date value from database which is in string format. i want convert it in to date format to find that, is proj_close_date present between from_date and to_date
public ArrayList viewAllCustProj1(String frm_date,String to_date,String cust,String proj)
{
ArrayList list= new ArrayList();
try
{
String strCust="";
String strproj="";
if(!cust.equalsIgnoreCase("ALL") && !cust.equals(null))
{
strCust="and customer_code='"+cust+"'";
}
if(!proj.equalsIgnoreCase("ALL") && !proj.equals(null))
{
strproj="and project_code='"+proj+"'";
}
if(cust.equalsIgnoreCase("ALL") && !proj.equalsIgnoreCase("ALL"))
{
}
else
{
stmt=conn.prepareStatement("select customer_code from mst_customer where visible=1 "+strCust+" and category='EU' and multiple_project=0");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code("");
list.add(bean);
}
rs.close();
stmt.close();
}
System.out.println(" select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
stmt=conn.prepareStatement("select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
String proj_close_date=rs.getString(3);
String added_on=rs.getString(4);
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
DateFormat myDateFormat1= new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate1 = null;
Date myDate2 = null;
Date myDate3 = null;
Date myDate4 = null;
Date myDate5 = null;
try
{
if(proj_close_date==null || proj_close_date.trim().equals("") || proj_close_date=="NULL")
{
System.out.println("\n ****** In IF Loop ");
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
System.out.println("\n ****** In Else Loop ");
myDate1 = myDateFormat.parse(proj_close_date);
myDate2 = myDateFormat.parse(frm_date);
myDate3 = myDateFormat.parse(to_date);
myDate5 = myDateFormat1.parse(added_on);
//myDate4 = myDateFormat.format(myDate5);
System.out.println("Project Code ---->"+rs.getString(2));
System.out.println("Proj_close_date ------>"+myDate1);
System.out.println("From Date ---->"+myDate2);
System.out.println("to Date ---->"+myDate3);
//System.out.println("Added_on --->"+myDate4);
System.out.println("Added_on 1 ie Date 5 ---->"+myDate5);
if(myDate1.after(myDate2) && myDate1.before(myDate3)) // means --> if(proj_close_date.after(frm_date) && proj_close_date.before(to_date))
{
if(myDate1.after(myDate4)) // means --> if(proj_close_date.after(added_on))
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
}//if
}//else
}//try
catch (ParseException e)
{
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
rs.close();
stmt.close();
}
catch(SQLException sex)
{
sex.printStackTrace();
}
finally
{
closeConnection();
}
return list;
}
Change this line
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
to this:
DateFormat myDateFormat = new SimpleDateFormat("MM/dd/yyyy");
However, it's quite unclear why you get all the values as strings, perhaps you should consider dedicated ResultSet methods such as getDate or getTimeStamp.
As another side remark I'd like to mention that building SQL queries by concatenation should be avoided -- you should generate queries with ? placeholders, and then set the parameters on your PreparedStatement.
Related
I written following code but it throws a "Resultset exhausted" error.
String dt = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat1.parse(dt);
DateTime dateTime = new DateTime(date);
Integer attributeID = 0;
String query1 ="select distinct M_attributesetinstance_id from M_storage where m_Product_id="+M_Product_ID;
attributeID = DB.getSQLValue(trxName, query1);
Timestamp MaufacuringDate = null;
String query = "select manufacturingdate from m_attributesetinstance where m_attributesetinstance_id="+attributeID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (MaufacuringDate!= null)
{
DateTime ManufacturingDate = new DateTime(MaufacuringDate);
try
{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate != null)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
DateTime dateTime1 = new DateTime(d1);
try
{
// c1.setTime(sdf.parse(dt));
// ReadableInstant date2;
Days d = Days.daysBetween(ManufacturingDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}
catch (Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
catch (ParseException e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else
{
continue;
}
}
catch(Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.after(GuaranteeDate))
{
continue;
}
}
else
{
Timestamp GRNDate = null;
String query2 = "select distinct Movementdate from M_inout m "
+"inner join m_inoutline mil ON (m.M_Inout_ID = mil.M_Inout_id) where mil.M_Product_Id="+M_Product_ID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query2.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
GRNDate = rs.getTimestamp("Movementdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
// String dt1 = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dateFormat1.parse(dt);
DateTime dateTime2 = new DateTime(date1);
DateTime GRDate = new DateTime(GRNDate);
try{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate!=null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
//DateTime dateTime1 = new DateTime(d1);
try {
// c1.setTime(sdf.parse(dt));
//ReadableInstant date2;
Days d = Days.daysBetween(GRDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}catch(Exception e){
MinGuaranteeDate = null;
e.printStackTrace();
}
} catch (ParseException e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else {
continue;
}
}catch(Exception e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.before(GuaranteeDate)) {
continue;
}
}
}
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
}
}
} catch (Exception e) {
s_log.log(Level.SEVERE, sql, e);
} finally {
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
in above code gives the error on statement of bigdecimal
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
on this line
Kindly help me out
You need to find out whether MStorage calls rs.next() again, as you already used up all the results within another block:
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
I guess you have iterated over the record using Resultset object rs and now your rs cursor is at the end of the record/ or we can say it not pointing to any record.
Still your code below is using rs object which is exhausted and not pointing to any record/table row.
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
Possible solution :: Create a new statement, execute query and get the new ResultSet object whose cursor will be at the start of record (Note: Cursor at -1 (use .next())) and iterate over the record ad get the required result.
OR use some logic inside previous iteration over record and get the result there itself instead of iterating again .
I am trying to get date in my database that have format like this "dd/MM/yyyy" and compare them to get latest date..
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me. Any suggestions? It seems like this should be an easy feat to accomplish.
from String last_updatedArr[]'s array result :
12/11/2015
12/11/2015
12/11/2015
12/11/2015
12/11/2015
13/11/2015
Method:
public String latestDate(){
String last_updated=null;
try {
String last_updatedDb=null;
String query = "SELECT Last_updated FROM Mattress";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs= pst.executeQuery();
String last_updatedArr[]=new String[100];
while(rs.next()){
int i = 0;
last_updatedDb=rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i]=last_updatedDb;
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
for(int i =0;i<last_updatedArr.length;i++){
date1 = (java.sql.Date)sdf.parse(last_updatedArr[i]);
date2 = (java.sql.Date)sdf.parse("1/1/2010");
if(date1.after(date2)){
//Date1 is after Date2
last_updated= sdf.format(date1);
}
if(date1.before(date2)){
//Date1 is before Date2
last_updated= sdf.format(date2);
}
if(date1.equals(date2)){
//Date1 is equal Date2
last_updated= sdf.format(date1);
}
}
} catch (ParseException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return last_updated;
}
Your loop resets i on every iteration. Move the declaration of i in your while loop. Or just use a for loop. Like,
for(int i = 0; rs.next(); i++) {
last_updatedDb = rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i] = last_updatedDb;
}
or something like,
int i = 0;
while(rs.next()){
// int i = 0;
last_updatedArr[i] = rs.getString("Last_updated");
System.out.println(last_updatedArr[i]);
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
// reuse i from while loop...
for(i = 0; i < last_updatedArr.length; i++){
I am trying to insert date into mysql. The field is of date type
but when I select a date from datepicker and insert it into database,it takes a random date..not getting where the problem is..
the code is as follow:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date d = null;
Date parsed = null;
try {
parsed = format.parse(request.getParameter("dt"));
System.out.println(parsed);
if (parsed != null) {
d = new java.sql.Date(parsed.getTime()); //parsed.getTime(
System.out.println(d);
} else {
d = new java.sql.Date(new Date().getTime());
}
} catch (ParseException e1) {
e1.printStackTrace();
}
String nature = request.getParameter("call_nature");
String name = request.getParameter("c_name");
String cat = request.getParameter("call").toString();
String num = request.getParameter("phone_no");
String street = request.getParameter("streetno").toString();
String rbut = request.getParameter("c_room");
String val = request.getParameter("hidd");
String zone = request.getParameter("combo1").toString();
String div = request.getParameter("combo2");
String hrs = request.getParameter("hr1");
String mns = request.getParameter("mn1");
String am = request.getParameter("ap1");
String occup = request.getParameter("occu");
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionurl = "jdbc:mysql://localhost:3306/fms";
String user = "root";
String pass = "root";
Connection con = DriverManager.getConnection(connectionurl, user, pass);
String sql = "insert into fire_reg values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prst = con.prepareStatement(sql);
prst.setString(1, nature);
prst.setString(2, cat);
prst.setString(3, name);
prst.setString(4, num);
prst.setString(5, val);
prst.setString(6, street);
prst.setDate(7, d);
prst.setString(8, rbut);
prst.setString(9, zone);
prst.setString(10, div);
prst.setString(11, hrs);
prst.setString(12, mns);
prst.setString(13, am);
prst.setString(14, occup);
if (prst.executeUpdate() == 1) {
request.setAttribute("loc", street);
//System.out.println(street);
request.setAttribute("phone", num);
request.setAttribute("calltypee", cat);
request.setAttribute("zonee", zone);
RequestDispatcher rd = request.getRequestDispatcher("FMS14_DelhiRegMap.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
System.out.println(e);
}
I've got a method, that returns the value of a ResultSet query via a date object. The snag is that, in my output, it only returns the last value in the particular column. How do i go about this?
public Date getTime(){
Date date = null;
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return date;
}
Then in my main method:
public static void main(String args[]){
TestA ea = new TestA();
Date ss = ea.getTime();
System.out.println(ss);
}
But this only returns the last value in my query. how can i print out other (the olders) along with it?
You need to fill a list of dates from your query results. Try this :
public List<Date> getTime(){
List<Date> dates = new ArrayList<Date>();
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
dates.add((Date)format.parse(ds));
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return dates;
}
Because of the while loop you asign to date the last value.
Change your method as
public List<Date> getTime(){
You can try
List<Date> dates = new ArrayList<Date>();
and then inside your while loop;
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
dates.put(date);
}
return dates;
just:
List<Date> lDateDb = new ArrayList<Date>();
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
lDateDb.add(date);
}
return lDateDb;
change return type of getTime to List<Date> and change the main to:
public static void main(String args[]){
TestA ea = new TestA();
List<Date> lAllDate = ea.getTime();
for (Date lDate : lAllDate)
System.out.println(lDate );
}
my application takes in a string like this "2002-10-15 10:55:01.000000". I need to validate that the string is a valid for a db2 timestamp.
How can I do this?
EDIT: This mostly works
public static boolean isTimeStampValid(String inputString) {
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(inputString);
return true;
} catch (ParseException e) {
return false;
}
}
The problem is that if I pass it a bad format for milliseconds like "2011-05-02 10:10:01.0av" this will pass validation. I am assuming that since the first millisecond character is valid then it just truncates the rest of the string.
I'm not exactly sure about the format but you you can play around it and can try something like this
public static bool isTimeStampValid(String inputString)
{
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try{
format.parse(inputString);
return true;
}
catch(ParseException e)
{
return false;
}
}
EDIT: if you want to validate for numbers after successful parsing, you could do
format.parse(inputString);
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
return p.matcher(inputString).matches();
instead of
format.parse(inputString);
return true;
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
I believe the format would be "yyyy-MM-dd HH:mm:ss.SSSSSS"
Call parse(String) and catch ParseException indicating it is invalid.
/**
* This method validates the given time stamp in String format
* #param timestamp
* #return
*/
public static boolean isTimeStampValid(String timestamp) {
//(Considering that formal will be yyyy-MM-dd HH:mm:ss.SSSSSS )
//Tokenize string and separate date and time
boolean time = false;
try {
//Tokenize string and separate date and time
StringTokenizer st = new StringTokenizer(timestamp, " ");
if (st.countTokens() != 2) {
return false;
}
String[] dateAndTime = new String[2];
int i = 0;
while (st.hasMoreTokens()) {
dateAndTime[i] = st.nextToken();
i++;
}
String timeToken = dateAndTime[1];
StringTokenizer timeTokens = new StringTokenizer(timeToken, ":");
if (timeTokens.countTokens() != 3) {
return false;
}
String[] timeAt = new String[4];
int j = 0;
while (timeTokens.hasMoreTokens()) {
timeAt[j] = timeTokens.nextToken();
j++;
}
try {
int HH = Integer.valueOf(timeAt[0].toString());
int mm = Integer.valueOf(timeAt[1].toString());
float ss = Float.valueOf(timeAt[2].toString());
if (HH < 60 && HH >= 0 && mm < 60 && mm >= 0 && ss < 60 && ss >= 0) {
time = true;
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
//Got Date
String dateToken = dateAndTime[0];//st.nextToken();
//Tokenize separated date and separate year-month-day
StringTokenizer dateTokens = new StringTokenizer(dateToken, "-");
if (dateTokens.countTokens() != 3) {
return false;
}
String[] tokenAt = new String[3];
//This will give token string array with year month and day value.
int k = 0;
while (dateTokens.hasMoreTokens()) {
tokenAt[k] = dateTokens.nextToken();
k++;
}
//Now try to create new date with got value of date
int dayInt = Integer.parseInt(tokenAt[2]);
int monthInt = Integer.parseInt(tokenAt[1]);
int yearInt = Integer.parseInt(tokenAt[0]);
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.set(yearInt, monthInt - 1, dayInt);
cal.getTime();//If not able to create date it will throw error
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Here we ll check for correct format is provided else it ll return false
try {
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
if (p.matcher(timestamp).matches()) {
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Cross checking with simple date format to get correct time stamp only
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(timestamp);
//return true;
if (time) {
return true;
} else {
return false;
}
} catch (ParseException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
If you're already connected to the database, you can execute a query that attempts to cast the input string as a timestamp, and check for a failure message (in this case, SQLSTATE 22007).
VALUES CAST( ? AS TIMESTAMP )
The above query will fully validate the input string while consuming hardly any resources on the database server. If the string is invalid for any reason, your database client will encounter an exception.