Given first chrono time, calculate value of next results given the gaps - java

I have some sports time results returned by an xml feed.
Result time for the first arrived is returned and converted like this:
String time = "00:01:00:440";
String gap = "";
for the other partecipants I get back only the gap:
String time = "";
String gap = "00:00:00:900";
How can I calculate the time of others partecipants given the gap from the first?
I have tried with java Date object but it uses calendar days too and I get strange result:
String firstTime = "00:01:00:440";
String gapOne = "00:00:00:900";
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss:SSS");
Date d1 = null;
Date d2 = null;
long diff = 0;
String timeResult = "";
try {
d1 = formatter.parse(firstTime);
d2 = formatter.parse(gapOne);
diff = d2.getTime() + d1.getTime();
timeResult = formatter.format(new Date(diff));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(timeResult);
But prints out:
11:01:01:340

I came up with this solution:
String firstTime = "00:01:00:440";
String gapOne = "00:00:00:900";
String firstTimeSplit[] = firstTime.split(":");
String gapSplit[] = gapOne.split(":");
int millisecSum = Integer.parseInt(firstTimeSplit[3]) + Integer.parseInt(gapSplit[3]);
int secsSum = Integer.parseInt(firstTimeSplit[2]) + Integer.parseInt(gapSplit[2]);
int minSum = Integer.parseInt(firstTimeSplit[1]) + Integer.parseInt(gapSplit[1]);
int hrsSum = Integer.parseInt(firstTimeSplit[0]) + Integer.parseInt(gapSplit[0]);
String millisec = String.format("%03d", millisecSum % 1000);
int mathSec = millisecSum / 1000 + secsSum;
String secs = String.format("%02d", mathSec % 60);
int mathMins = mathSec / 60 + minSum;
String mins = String.format("%02d", mathMins % 60);
int mathHrs = mathMins / 60 + hrsSum;
String hrs = String.format("%02d", mathHrs % 60);
String format = "%s:%s:%s:%s";
String result = String.format(format, hrs, mins, secs, millisec);
This way I get returned the value this way:
00:01:01:340

Related

Java calculate time difference between check in and out

I want to calculate the time difference hour and minute without using java dateformat
user should input like
Clock In: 23:00
Clock Out: 01:00
The expected output shall be something like 2 hours 00 minutes.
But how can I calculate them?
Scanner input = new Scanner(System.in);
//Read data
System.out.print("Clock In: ");
String sTimeIn = input.nextLine();
System.out.print("Clock Out: ");
String sTimeOut = input.nextLine();
// Process data
String sHourIn = sTimeIn.substring(0, 2);
String sMinuteIn = sTimeIn.substring(3, 5);
String sHourOut = sTimeOut.substring(0, 2);
String sMinuteOut = sTimeOut.substring(3, 5);
int iHourIn = Integer.parseInt(sHourIn);
int iMinuteIn = Integer.parseInt(sMinuteIn);
int iHourOut = Integer.parseInt(sHourOut);
int iMinuteOut = Integer.parseInt(sMinuteOut);
int sumHour =
int sumMinute =
//Display Output
System.out.print(sumHour +"Hour "+ sumMinute + " Minute");
}
}
After I have reviewed all the solutions you given. Here is what I have edited. But I still found an issue is,
if Clock in 23:00 Clock Out: 01:00 and the output is 22Hour(s) 0 Minute(s). The output should be 02 Hour(s) 0 Minute(s).
System.out.println("*Your time format must be 00:00");
System.out.print("Clock In: ");
String getTimeIn = input.nextLine();
System.out.print("Clock Out: ");
String getTimeOut = input.nextLine();
// Process data
String sHourIn = getTimeIn.substring(0, 2);
String sMinuteIn = getTimeIn.substring(3, 5);
String sHourOut = getTimeOut.substring(0, 2);
String sMinuteOut = getTimeOut.substring(3, 5);
int sumHour = Integer.parseInt(sHourIn) - Integer.parseInt(sHourOut);
int sumMinute = Integer.parseInt(sMinuteIn) - Integer.parseInt(sMinuteOut);
if(sumHour < 0) {
sumHour =-sumHour;
}
if(sumMinute < 0) {
sumMinute =- sumMinute;
}
//Display Output
System.out.print(sumHour +"Hour(s) "+ sumMinute + " Minute(s)");
If you want to use LocalTime and ChronoUnit classes of Java 8:
String sTimeIn = "23:15";
String sTimeOut = "1:30";
LocalTime timeIn = LocalTime.parse(sTimeIn, DateTimeFormatter.ofPattern("H:m"));
LocalTime timeOut = LocalTime.parse(sTimeOut, DateTimeFormatter.ofPattern("H:m"));
long dif = ChronoUnit.MINUTES.between(timeIn, timeOut);
if (dif < 0)
dif += 24 * 60;
long sumHour = dif / 60;
long sumMinute = dif % 60;
System.out.println(sumHour + ":"+ sumMinute);
or formatted to HH:mm:
System.out.println(String.format("%02d", sumHour) + ":"+ String.format("%02d", sumMinute));
will print:
02:15
As #Stultuske said the time library should be a safer option, I have provided an example below
import java.time.LocalTime;
public class HelloWorld
{
public static void main(String[] args)
{
LocalTime in = LocalTime.parse("18:20");
LocalTime out = LocalTime.parse("20:30");
int hoursDiff = (out.getHour() - in.getHour()),
minsDiff = (int)Math.abs(out.getMinute() - in.getMinute()),
secsDiff = (int)Math.abs(out.getSecond() - in.getSecond());
System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
}
}
Update:
The solution is missing the midnight crossing as pointed by #Joakim Danielson, So I have modified the above solution to check for in > out or out < in.
import java.time.LocalTime;
public class HelloWorld
{
public static void main(String[] args)
{
LocalTime in = LocalTime.parse("16:00");
LocalTime out = LocalTime.parse("01:00");
int hOut = out.getHour(),
hIn = in.getHour();
int hoursDiff = hOut < hIn ? 24 - hIn + hOut : hOut - hIn,
minsDiff = (int)Math.abs(out.getMinute() - in.getMinute()),
secsDiff = (int)Math.abs(out.getSecond() - in.getSecond());
System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
}
}
Here is my suggested solution including some simple (not perfect) validation of the input, I have put the solution inside a method so asking user for input is not handled
public static void calcTime(String sTimeIn, String sTimeOut) {
final String timePattern = "[0-2][0-9]:[0-5][0-9]";
if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
throw new IllegalArgumentException();
}
String[] timeIn = sTimeIn.split(":");
String[] timeOut = sTimeOut.split(":");
int inMinutes = 60 * Integer.valueOf(timeIn[0]) + Integer.valueOf(timeIn[1]);
int outMinutes = 60 * Integer.valueOf(timeOut[0]) + Integer.valueOf(timeOut[1]);
int diff = 0;
if (outMinutes > inMinutes) {
diff = outMinutes - inMinutes;
} else if (outMinutes < inMinutes) {
diff = outMinutes + 24 * 60 - inMinutes;
}
System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut, diff / 60, diff % 60);
}
Update
Here is a solution based on LocalTime and Duration
public static void calcTime2(String sTimeIn, String sTimeOut) {
final String timePattern = "[0-2][0-9]:[0-5][0-9]";
if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
throw new IllegalArgumentException();
}
String[] timeIn = sTimeIn.split(":");
String[] timeOut = sTimeOut.split(":");
LocalTime localTimeIn = LocalTime.of(Integer.valueOf(timeIn[0]), Integer.valueOf(timeIn[1]));
LocalTime localTimeOut = LocalTime.of(Integer.valueOf(timeOut[0]), Integer.valueOf(timeOut[1]));
Duration duration;
if (localTimeOut.isAfter(localTimeIn)) {
duration = Duration.between(localTimeIn, localTimeOut);
} else {
Duration prevDay = Duration.ofHours(24).minusHours(localTimeIn.getHour()).minusMinutes(localTimeIn.getMinute());
Duration nextDay = Duration.between(LocalTime.MIDNIGHT, localTimeOut);
duration = prevDay.plus(nextDay);
}
System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut,
duration.toHours(), duration.minusHours(duration.toHours()).toMinutes());
}
try this :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Read data
System.out.println("Clock In: ");
String sTimeIn = "20:30";
System.out.println("Clock Out: ");
String sTimeOut = "18:20";
// Process data
String sHourIn = sTimeIn.substring(0, 2);
String sMinuteIn = sTimeIn.substring(3, 5);
String sHourOut = sTimeOut.substring(0, 2);
String sMinuteOut = sTimeOut.substring(3, 5);
int iHourIn = Integer.parseInt(sHourIn);
int iMinuteIn = Integer.parseInt(sMinuteIn);
int iHourOut = Integer.parseInt(sHourOut);
int iMinuteOut = Integer.parseInt(sMinuteOut);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,iHourIn);
cal.set(Calendar.MINUTE,iMinuteIn);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Long timeIn = cal.getTime().getTime();
cal.set(Calendar.HOUR_OF_DAY,iHourOut);
cal.set(Calendar.MINUTE,iMinuteOut);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Long timeOut = cal.getTime().getTime();
Long finaltime= timeIn-timeOut;
// Convert the result to Hours and Minutes
Long temp = null;
// get hours
temp = finaltime % 3600000 ;
int sumHour = (int) ((finaltime - temp) / 3600000 );
finaltime = temp;
int sumMinute = (int) (finaltime/ 60000);
//Display Output
System.out.println(sumHour +" Hour "+ sumMinute + " Minute");
}
I have added some code in addition to your code. Please check and let me know if this is enough for your requirement
public class MainClass1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Read data
System.out.print("Clock In: ");
String[] sTimeIn = input.nextLine().split(":");
System.out.print("Clock Out: ");
String[] sTimeOut = input.nextLine().split(":");
int iHourIn = Integer.parseInt(sTimeIn[0]);
int iMinuteIn = Integer.parseInt(sTimeIn[1]);
int iHourOut = Integer.parseInt(sTimeOut[0]);
int iMinuteOut = Integer.parseInt(sTimeOut[1]);
if(iMinuteIn < iMinuteOut) {
iMinuteIn = 60 + iMinuteIn;
iHourIn--;
}
int sumHour = iHourIn - iHourOut;
int sumMinute = iMinuteIn - iMinuteOut;
//Display Output
System.out.print(sumHour +"Hour "+ sumMinute + " Minute");
}
}

Java format hour and min

I need to format my time string such as this:
int time = 160;
Here's my sample code:
public static String formatDuration(String minute) {
String formattedMinute = null;
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse(minute);
sdf = new SimpleDateFormat("HH mm");
formattedMinute = sdf.format(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedMinute;
// int minutes = 120;
// int h = minutes / 60 + Integer.parseInt(minute);
// int m = minutes % 60 + Integer.parseInt(minute);
// return h + "hr " + m + "mins";
}
I need to display it as 2hrs 40mins. But I don't have a clue how to append the "hrs" and "mins". The requirement is not to use any library.
If you've done something like this in the past, feel free to help out. Thanks a bunch!
Since, it's 2018, you really should be making use of the Date/Time libraries introduced in Java 8
String minutes = "160";
Duration duration = Duration.ofMinutes(Long.parseLong(minutes));
long hours = duration.toHours();
long mins = duration.minusHours(hours).toMinutes();
// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);
System.out.println(formatted);
Which outputs...
2hrs 40mins
Why use something like this? Apart of generally been a better API, what happens when minutes equals something like 1600?
Instead of printing 2hrs 40mins, the above will display 26hrs 40mins. SimpleDateFormat formats date/time values, it doesn't deal with duration
int minutes = 160;
int h = minutes / 60;
int m = minutes % 60;
String.format("%d hr %d mins",h,m); // output : 2 hr 40 mins
Just try
sdf = new SimpleDateFormat("HH 'hrs' mm 'mins'");
There is a good documentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
From the doc:
"Text can be quoted using single quotes (') to avoid interpretation."
Another simple approach could be something along the lines:
public static String formatDuration(String minute){
int minutes = Integer.parseInt(minute);
int hours = minutes / 60;
minutes = minutes % 60;
return hours + "hrs " + minutes + "mins.";
}

java.sql.SQLException: Illegal hour value '50' for java.sql.Time type in value '50:51:05

When I try to retrieve time from MySQL and set it to a JLabel, it gives me an error.
java.sql.SQLException: Illegal hour value '50' for java.sql.Time type
in value '50:51:05.
Can anyone suggest me how to fix this?
Code is as follows.
String sql = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ot)))"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
st = con.createStatement();
rst = st.executeQuery(sql);
if(rst.next())
{
String time = rst.getString(1);
oTimeTemp.setText(time);
}
I solved it. Here is the code,
String sql = "SELECT SUM(TIME_TO_SEC(ot))"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
st = con.createStatement();
rst = st.executeQuery(sql);
if(rst.next())
{
String time = rst.getString(1);
Double dTime = Double.valueOf(time);
int intTime = (int) dTime.doubleValue();
String nTime = calculateTime(intTime);
oTimeTemp.setText(nTime);
}
private static String calculateTime(int totalSecs)
{
int hours = totalSecs / 3600;
int minutes = (totalSecs % 3600) / 60;
int seconds = totalSecs % 60;
String timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return timeString;
}
There is a mysql bug , use it as follows it would work fine:
String sql = "SELECT concate(SEC_TO_TIME(SUM(TIME_TO_SEC(ot))),'')"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
// if you want to use time as label
// you can use oTimeTemp if Date type of java.util, this have both time and date
if(rst.next())
{
// this Time string need to cast in util time
String time = rst.getString(1);
String time = time ;
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
oTimeTemp.setText(date); // in this date we have the time
}

Need to check for available dates in a for loop and schedule a sale order

I have a MS SQL server table having these columns - Date_Allotted, Sale_Order_No, Time_Available.
The contents are like -
Date_Allotted | Sale_Order_No | Time_Available | Time_Needed
-------------------------------------------------------------------
02-02-2015 | 123456 | 90 mins | 50 mins
08-02-2015 | 123457 | 70 mins | 30 mins
09-02-2015 | 123458 | 120 mins | 200 mins
10-02-2015 | 123459 | 320 mins | 100 mins
11-02-2015 | 123455 | 40 mins | 20 mins
15-02-2015 | 123454 | 30 mins | 15 mins
Time_Available says, how many minutes are available from morning 9 to evening 6:30.
Time_Needed says, number of minutes the sale order needs to get executed.
When a new sale order is added, I want to schedule it when the dates are free, i.e., when on the date there is no sale order scheduled. I need to check the dates in between and check if time is available on that day in a loop.
I am using the following code to get the dates which are not in the series and the dates between them.
I mean, in the above dates, 8th and 9th are in series and dates are available between 2nd and 8th, 9th and 11th and 11th and 15th.
The code is -
To find dates between 2 dates..........
Declare #Date1 DATETIME, #Date2 DATETIME
set #Date1 = '01/25/2015 12:00:00 AM';
set #Date2 = '02/05/2015 12:00:00 AM';
with daterange as
( select dt = DATEADD(dd, 1, #Date1)
where DATEADD(dd, 1, #Date1) <= #Date2
union all
select DATEADD(dd, 1, dt)
from daterange
where DATEADD(dd, 1, dt) <= #Date2 )
select *
from daterange
To find the dates not in series or the dates that have a gap............
select l.DateAllotted as start
from [DCP].[dbo].[TimeAllotted] as l
left outer join [DCP].[dbo].[TimeAllotted] as r on l.DateAllotted + 1 = r.DateAllotted
where r.DateAllotted is null
My function in java is something like this........
try
{
String tl = "";
SimpleDateFormat sdft = new SimpleDateFormat("HH:mm:ss");
st5 = con.createStatement();
ResultSet rs5 = st5.executeQuery("Select TimeLeft from DCP.dbo.TimeAllotted where DateAllotted = '"+lir.trim()+"'");
while(rs5.next())
{
tl = rs5.getString("TimeLeft"); // it is the time left on that day
System.out.println("TimeLeft : " + tl);
}
rs5.close();
st5.close();
if((("").equals(tl.trim())) || ((" ").equals(tl.trim())))
tl = "960";
int ftl = 0, frt = 0;
tl = tl.trim();
RoutingTime = RoutingTime.trim(); // it is the time needed to execute a sale order
ftl = Integer.parseInt(tl);
System.out.println("ftl: " + ftl);
frt = Integer.parseInt(RoutingTime);
System.out.println("frt: " + frt);
if(ftl >= frt)
{
Calendar calb = Calendar.getInstance();
Calendar calc = Calendar.getInstance();
Calendar cald = Calendar.getInstance();
String cdatet = "18:30:00";
calb.setTime(sdft.parse(cdatet));
cdatet = sdft.format(calb.getTime());
System.out.println("Fixed Date Time: " + cdatet);
String cdateta = "09:00:00";
cald.setTime(sdft.parse(cdateta));
cdateta = sdft.format(cald.getTime());
System.out.println("Fixed Date Time 1: " + cdateta);
String cdatetc = sdft.format(calc.getTime());
calc.setTime(sdft.parse(cdatetc));
cdatetc = sdft.format(calc.getTime());
System.out.println("Current Date Time: " + cdatetc);
java.util.Date cdatetd = calb.getTime();
java.util.Date cdatetcd = calc.getTime();
java.util.Date cdatetcd1 = cald.getTime();
int mins = (int) ((calb.getTime().getTime() - calc.getTime().getTime()) / (60000));
System.out.println("mins : " + mins);
int TimeLeft = 0;
if((cdatetcd1.before(cdatetcd)) && (cdatetcd.before(cdatetd)) && (mins >= frt))
TimeLeft = ftl - frt;
Statement st3 = con.createStatement();
String dd = "";
String sql1 = "SELECT datediff(dd, LastItemReceiptDate, CustomerRequestDate) as 'ddiff' FROM DCP.dbo.DCPDate where SONo = '"+jtfSONo.getText().trim()+"' and LineItemNo = '"+jtfLineItemNo.getText().trim()+"'";
ResultSet rs2 = st2.executeQuery(sql1);
while(rs2.next())
{
dd = rs2.getString("ddiff");
}
rs2.close();
st3.close();
int datediff = 0;
datediff = Integer.parseInt(dd);
System.out.println("datediff : " + datediff);
tl = "" + TimeLeft;
if(datediff >= 10)
{
if(TimeLeft <= frt)
{
Statement st6 = con.createStatement();
ArrayList<String> solist = new ArrayList<String>();
String sql2i = "select l.DateAllotted as start from [DCP].[dbo].[TimeAllotted] as l left outer join [DCP].[dbo].[TimeAllotted] as r on l.DateAllotted + 1 = r.DateAllotted where r.DateAllotted is null and l.DateAllotted > '"+lir.trim()+"'"; // check which date are not in series
ResultSet rs6 = st6.executeQuery(sql2i);
while(rs6.next())
{
solist.add(rs6.getString("Start").trim());
}
rs6.close();
st6.close();
for(int i = 0; i < solist.size(); i++)
{
for(int j = i; j <= (i+1); j++)
{
Statement st7 = con.createStatement();
ArrayList<String> linelist = new ArrayList<String>();
String sql3 = "Declare #sDate DATETIME, #eDate DATETIME select #sDate = '"+solist.get(i).toString().trim()+"'; select #eDate = '"+solist.get(i+1).toString().trim()+"'; ;with DATE(Date1) as ( select DATEADD(day, datediff(day, '19000101', #sDate), '19000101') union all select DATEADD(day, 1, Date1) from DATE where Date1 <= #eDate ) select convert(varchar(15),d1.DATE1,110) as [Working Date], datename(weekday,d1.Date1)[Working Day] from DATE d1 where (datename(weekday,d1.Date1))not in ('Saturday','Sunday')"; // check free dates using the dates not in series and consider only working dates
ResultSet rs7 = st7.executeQuery(sql3);
while(rs7.next())
{
linelist.add(rs7.getString("Working Date").trim());
}
for(int k = 0; k < linelist.size(); k++)
{
Statement st8 = con.createStatement();
String lefttime = "";
ResultSet rs8 = st8.executeQuery("Select TimeLeft from DCP.dbo.TimeAllotted where DateAllotted = '"+linelist.get(k).toString().trim()+"'"); // take up one date, if time is available, come out of the loop and schedule the sale order on that date.....
while(rs8.next())
{
lefttime = rs8.getString("TimeLeft");
System.out.println("TimeLeft : " + lefttime);
}
if((("").equals(lefttime.trim())) || ((" ").equals(lefttime.trim())))
lefttime = "960";
int ftla = 0, frta = 0;
lefttime = lefttime.trim();
RoutingTime = RoutingTime.trim();
ftla = Integer.parseInt(lefttime);
System.out.println("ftla: " + ftla);
frta = Integer.parseInt(RoutingTime);
System.out.println("frta: " + frta);
if(ftla >= frta)
{
Calendar calbi = Calendar.getInstance();
Calendar calci = Calendar.getInstance();
Calendar caldi = Calendar.getInstance();
String cdateti = "18:30:00";
calbi.setTime(sdft.parse(cdateti));
cdateti = sdft.format(calbi.getTime());
System.out.println("Fixed Date Timei: " + cdateti);
String cdatetai = "09:00:00";
caldi.setTime(sdft.parse(cdatetai));
cdatetai = sdft.format(caldi.getTime());
System.out.println("Fixed Date Time 1i: " + cdatetai);
String cdatetci = sdft.format(calci.getTime());
calci.setTime(sdft.parse(cdatetci));
cdatetci = sdft.format(calci.getTime());
System.out.println("Current Date Timei: " + cdatetci);
java.util.Date cdatetdi = calbi.getTime();
java.util.Date cdatetcdi = calci.getTime();
java.util.Date cdatetcd1i = caldi.getTime();
int minsi = (int) ((calbi.getTime().getTime() - calci.getTime().getTime()) / (60000));
System.out.println("minsi : " + minsi);
int TimeLefti = 0;
if((cdatetcd1i.before(cdatetcdi)) && (cdatetcdi.before(cdatetdi)) && (minsi >= frta))
TimeLefti = ftla - frta;
lefttime = "" + TimeLefti;
if(TimeLefti >= frta)
{
EDCDate = linelist.get(k).toString().trim();
break;
}
}
}
}
}
calca.add(Calendar.DATE, 1);
// check if the date is free
lir = sdf1.format(calca.getTime());
System.out.println("lir : " + lir);
EDCDate = lir.trim();
}
else
{
EDCDate = lir.trim();
}
}
else
{
if(TimeLeft <= frt)
{
calda.add(Calendar.DATE, 1);
cr = sdf1.format(calda.getTime());
System.out.println("cr : " + cr);
EDCDate = cr.trim();
}
else
{
EDCDate = cr.trim();
}
}
}
else
{
Calendar cala = Calendar.getInstance();
String cdate = sdf.format(cala.getTime());
cala.setTime(sdf.parse(cdate));
cdate = sdf1.format(cala.getTime());
System.out.println("Current Date : " + cdate);
cala.add(Calendar.DATE, 1);
cdate = sdf1.format(cala.getTime());
System.out.println("cdate : " + cdate);
EDCDate = cdate.trim();
}
}
else
{
SimpleDateFormat sdft = new SimpleDateFormat("HH:mm:ss");
st5 = con.createStatement();
ResultSet rs5 = st5.executeQuery("Select TimeLeft from DCP.dbo.TimeAllotted where DateAllotted = '"+lir.trim()+"'");
while(rs5.next())
{
tl = rs5.getString("TimeLeft");
System.out.println("TimeLeft : " + tl);
}
rs5.close();
st5.close();
if((("").equals(tl.trim())) || ((" ").equals(tl.trim())))
tl = "960";
int ftl = 0, frt = 0;
tl = tl.trim();
RoutingTime = RoutingTime.trim();
ftl = Integer.parseInt(tl);
System.out.println("ftl: " + ftl);
frt = Integer.parseInt(RoutingTime);
System.out.println("frt: " + frt);
if(ftl >= frt)
{
Calendar calb = Calendar.getInstance();
Calendar calc = Calendar.getInstance();
Calendar cald = Calendar.getInstance();
String cdatet = "18:30:00";
calb.setTime(sdft.parse(cdatet));
cdatet = sdft.format(calb.getTime());
System.out.println("Fixed Date Time: " + cdatet);
String cdateta = "09:00:00";
cald.setTime(sdft.parse(cdateta));
cdateta = sdft.format(cald.getTime());
System.out.println("Fixed Date Time 1: " + cdateta);
String cdatetc = sdft.format(calc.getTime());
calc.setTime(sdft.parse(cdatetc));
cdatetc = sdft.format(calc.getTime());
System.out.println("Current Date Time: " + cdatetc);
java.util.Date cdatetd = calb.getTime();
java.util.Date cdatetcd = calc.getTime();
java.util.Date cdatetcd1 = cald.getTime();
int mins = (int) ((calb.getTime().getTime() - calc.getTime().getTime()) / (60000));
System.out.println("mins : " + mins);
int TimeLeft = 0;
if((cdatetcd1.before(cdatetcd)) && (cdatetcd.before(cdatetd)) && (mins >= frt))
TimeLeft = ftl - frt;
if(TimeLeft <= frt)
{
calca.add(Calendar.DATE, 1);
lir = sdf1.format(calca.getTime());
System.out.println("lir : " + lir);
EDCDate = lir.trim();
}
else
{
EDCDate = lir.trim();
}
}
else
{
Calendar cala = Calendar.getInstance();
String cdate = sdf.format(cala.getTime());
cala.setTime(sdf.parse(cdate));
cdate = sdf1.format(cala.getTime());
System.out.println("Current Date : " + cdate);
cala.add(Calendar.DATE, 1);
cdate = sdf1.format(cala.getTime());
System.out.println("cdate : " + cdate);
EDCDate = cdate.trim();
}
}
Please guide me.......... I am not sure about the loops. I need to first check for the dates not in series or the dates that have gap in between. And, then, using those dates, check which all dates are free. Then, check if time is available on that date. If yes, break the loop and schedule the order, else go to next date. Please tell me if the loops are correct or can they be improved on.
Create a calendar table in SQL. A table that has every date in it. Then join to it, so you can return all dates, even if they don't appear in your TimeAllotted table.

Android check days between two day-times

Hello everyone i try to check between days two daytimes
i have for example 12/10/2014 and 12/15/2015 datetimes.I wrote some code witch can to check different days between there two daytimes
this is a my source
public String getDateDiffString(Date dateOne, Date dateTwo) {
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return String.valueOf(delta);
} else {
delta *= -1;
return String.valueOf(delta);
}
}
this code working perfect but i want to increase days for example 12/10/2014, 12/11,2014.....12/20/2014 between first and second daytimes.i i also wrote code but result is between first date and second days -1(between 12/19/2014)
this is a my source
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date _d;
try {
SimpleDateFormat new_df = new SimpleDateFormat("d MMM");
_d = df.parse(timeInfo.getTimeformat().get(0));
Date _d1 = df.parse(timeInfo.getEndTimeFormat().get(0));
String datetimeis = getDateDiffString(_d1, _d);
int differentdays = Integer.parseInt(datetimeis);
Log.e("Different is ", "" + differentdays);
for (int k = 0; k < differentdays; k++) {
String datetimeformat = dateFormatter(timeInfo.getStartTimePeriod().get(0));
Date datetime = new_df.parse(datetimeformat);
Calendar cal = Calendar.getInstance();
cal.setTime(datetime);
cal.add(Calendar.DATE, k);
datetime = cal.getTime();
String ttime = new_df.format(datetime);
ApishaDaysAdapter.add(ttime);
ApishaHollsAdapter.add(timeInfo.getHole());
String start_time = timeInfo.getTime();
start_time = start_time.replace(",", "\n");
ApishaTimesAdapter.add(start_time);
timeInfo.setStartTimePeriod(ttime);
System.out.println(ttime);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
how i can solve my problem?if anyone knows solution please help me
i want to increase days [12 -20] and not [12-19)

Categories