Convert java.util.Date to java.sql.Date - java

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++){

Related

How can I draw gantt chart with date from database in java

I have problem in taking from the database the startdate and the finaldate of task to draw the chart
public IntervalCategoryDataset getCategoryDataset() {
conn = ConnectDB.ConnectDB();
TaskSeriesCollection dataset = new TaskSeriesCollection();
String sql = "SELECT `TITRE`, `DATE DEBUT Prévi`, `DATE FIN prévi` FROM `projet`;";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
String a = rs.getString("TITRE");
Date StartDate = rs.getDate("DATE DEBUT Prévi");
Date EndDate = rs.getDate("DATE FIN prévi");
Names.add(a);
Dates.add(StartDate);
Dates.add(EndDate);
++count;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
int j = 0;
int k = 1;
TaskSeries series1 = new TaskSeries("Estimated Date");
for (int i = 0; i < count; i++) {
series1.add(new Task(Names.get(i),
Date.from(LocalDate.of(Dates.get(j).getYear(), Dates.get(j).getMonth(), Dates.get(j).getDay())
.atStartOfDay()
.toInstant(ZoneOffset.UTC)),
Date.from(LocalDate.of(Dates.get(k).getYear(), Dates.get(k).getMonth(), Dates.get(k).getDay())
.atStartOfDay()
.toInstant(ZoneOffset.UTC))));
}
dataset.add(series1);
return dataset;
}
I expect to have for every tasks its chart but I have the same chart for all the tasks.
You should apply a single loop, and in addition either use getObject(index, LocalDate.class) or - if your driver doesn't support the previous option - java.sql.Date.toLocalDate():
public IntervalCategoryDataset getCategoryDataset() {
conn = ConnectDB.ConnectDB();
TaskSeriesCollection dataset = new TaskSeriesCollection();
TaskSeries series1 = new TaskSeries("Estimated Date");
String sql = "SELECT `TITRE`, `DATE DEBUT Prévi`, `DATE FIN prévi` FROM `projet`;";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("TITRE");
LocalDate startDate = rs.getObject("DATE DEBUT Prévi", LocalDate.class);
LocalDate endDate = rs.getObject("DATE FIN prévi", LocalDate.class);
series1.add(new Task(name,
Date.from(startDate.atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(endDate.atStartOfDay().toInstant(ZoneOffset.UTC)));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
dataset.add(series1);
return dataset;
}
You always get the same result because the j and k values are stacked in their default values and not incrementing along with the i counter in your for loop. Referring to the code am seeing, i advise you to get rid of the j and k counters, replace the j with i and the k with i+1.
Your for loop should be like the following:
for (int i =0; i<count; i++) {
series1.add(new Task(Names.get(i),
Date.from(LocalDate.of(Dates.get(i).getYear(), Dates.get(i).getMonth(),Dates.get(i).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(LocalDate.of(Dates.get(i+1).getYear(),Dates.get(i+1).getMonth(),Dates.get(i+1).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC))
)
);
}

How to increment date up to a certain date for inserting data?

I have a prepared statement like the one below inserting it to a postgres database:
String InsertQuery="INSERT INTO public.user_daily_activity (id,user,day,time)
values (?,?,?,?)";
String date="2017-11-16";
try{
jtmTemplate.update(InsertQuery, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setInt(1, id);
preparedStatement.setString(2, user);
preparedStatement.setDate(3, java.sql.Date.valueOf(date));
preparedStatement.setInt(4, time);
}
So now depending on the date I need to increment it from the start date to November 30. For example if date="2017-11-16" then I need to insert from "2017-11-16" to "2017-11-30". If date="2017-11-27" then I need to insert from "2017-11-27" to "2017-11-30".
Any help is appreciated.
Well, here you have a solution using pre-java8 Date and Calendar:
public void incrementDate() {
int dayLimit = 30;
// month is zero-based index
int monthLimit = 10;
String startStringDate = "2017-11-16";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
Date startDate;
java.sql.Date sqlDate;
try {
startDate = dateFormat.parse(startStringDate);
calendar.setTime(startDate);
while(calendar.get(Calendar.DAY_OF_MONTH) <= dayLimit && calendar.get(Calendar.MONTH) <= monthLimit) {
sqlDate = new java.sql.Date(startDate.getTime());
// here just use sqlDate in your prepared statement
//...
//e.g. preparedStatement.setDate(3, sqlDate);
// ...
System.out.println("Using sql date : " + sqlDate);
calendar.setTime(startDate);
calendar.add(Calendar.DATE, 1);
startDate = calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
}

Trying to update Date and Time in a loop

I want to print and update the date and time simultaneously. The following code only takes the time once and prints the same time 40 times. How can I update the time while printing it?
public class Dandm {
public static void main(String args[]) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String time = df.format(date);
int i;
for (i = 40; i > 0; i--) {
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
}
}
Replace System.out.println(date); with System.out.println(new Date());
The problem is, when you do Date date = new Date(); then date value doesn't change in the loop. You need a new date every time, so you should create a new Date() object every time.
Edit based on the comments (To get date as a string with only time):
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
for(i = 40; i > 0; i--){
Date date = new Date();
String str = sdf.format(date);
System.out.println(str);
try{Thread.sleep(500);}
catch (InterruptedException e){}
}
You are creating your object one time only, once your object is created it acquires its properties:
Date date = new Date();
If you want to update your time along side printing it, then either you would create the object within the loop like this:
for (i = 40; i > 0; i--) {
Date date = new Date();
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
Or just create an anonymous Date object in the print function.
for (i = 40; i > 0; i--) {
System.out.println(new Date());
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}

Exhausted Resultset SQL Exception occur in if condition else condition

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 .

Parse Error in Java Program

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.

Categories