Calculating difference in days between dates with vectors - java

Based on the post Calculating difference in days between dates
How do I feed the vectors vE and vS with random dates and then return the difference between your dates? Recalling that vS must be greater than vE? Actually, I should separate into two methods: a randomized dates and other calculates the difference.
/*
* Randomizacao
*/
package random04DiferencaDataVetor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class Random04DiferencaDataVetor {
public static void main(String[] args) throws ParseException {
final long intervalo = 1000000000;
Random rnd = new Random();
String[] vE = new String[5];
String[] vS = new String[5];
for (int i = 0; i < vE.length; i++) {
/*
* arrumar vetores para gerar datas aleatorias
* lembrando que vS deve ser maior que vE
*/
retornaData();
}
}
static void retornaData() throws ParseException {
final long intervalo = 1000000000;
Random rnd = new Random();
// formatando as datas
DateFormat formato = new SimpleDateFormat("yyyy");
Date anoE = formato.parse("2012");
long timeE = anoE.getTime();
Date anoS = formato.parse("2013");
long timeS = anoS.getTime();
// define o intervalo de datas em 1 ano
long tempoIntervalo = timeE - timeS;
// randomiza a data de entrada
long rndTempoE = timeE + (long) (rnd.nextDouble() * tempoIntervalo);
// data entrada
String dataE = new SimpleDateFormat("hh:mm dd/MM/yyyy").format(rndTempoE);
// randomiza a data de saida
long rndTempoS = rndTempoE + (long) (rnd.nextDouble() * intervalo * 2);
// data de saida
String dataS = new SimpleDateFormat("hh:mm dd/MM/yyyy").format(rndTempoS);
// formato de data
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
try {
Date dataEnt = sdf.parse(dataE);
Date dataSaida = sdf.parse(dataS);
long differenceMilliSeconds = dataSaida.getTime() - dataEnt.getTime();
long days = differenceMilliSeconds / 1000 / 60 / 60 / 24;
long hours = (differenceMilliSeconds % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60;
long minutes = (differenceMilliSeconds % (1000 * 60 * 60)) / 1000 / 60;
System.out.println(days + " days, " + hours + " hours, " + minutes + " minutes.");
} catch (ParseException e) {
e.printStackTrace();
}
}
}

You have declared Array not the Vector. You may use `Vector declaration as below:
Vector<String> vE = new Vector<String>();
Vector<String> vS = new Vector<String>();
But you may want to use List/ArrayList in place of Vector as below:
List<String> vE = new ArrayList<String>();
List<String> vS = new ArrayList<String>();
To add the date strings in the vectors, you can use add method as below:
String dateString1 = "01/01/2012";
vE.add(dateString1);
To add 5 dates your Vector vE, you may do as below:
for (int i = 0; i < 5; i++) {
int day = 1+ rnd.nextInt(28); //day from 1 to 28
int month = 1+rnd.nextInt(12); //day from 1 to 12
int year = 2000 +rnd.nextInt(13); //year from 2000 to 2012
String dateString = month+"/"+day+"/"year;
vE.add(dateString);
}
You may want to pass Vector vE in your retornaData(); method to compute the differences:
//call in `main` method outside the `for` loop as:
retornaData(vE);
//change method signature as
static void retornaData(Vector<String> vE) throws ParseException {
Inside retornaData(), you may want to retrieve two date string and compute the difference:
String date1 = vE.get(0);//use some index
String date2 = vE.get(1); //use some index
//compute the difference between date1 and date2
If you could use English in your sample program, I may try advising further corrections/improvements.

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");
}
}

Flipping images from PM to AM time

I am having set of 8 images. Here the images will be flipping according to the time which is set by the user and their will be default wake up time 7:00am. If the user sets the time at 10:10pm and the wake up time is 7:00am. Now, the images needs to flip and the flipping of images are in percentage wise i.e; 0% 20% 40% 60% 80% 90% 95% 100% of the total time. Now, the images are flipping when i am setting the time from 10:00am to 7:00pm , 9:00am to 11:00am , 7:00pm to 8:30pm etc. But when i am setting from 10:00pm to 7:00am the images are not flipping.
c = Calendar.getInstance();
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
twwntyhrformat = displayFormat.format(c.getTime());
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm a");
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
String time = timegot.getString("savedwakeuptime", "");
try {
Date date = parseFormat.parse(time);
String gottime = displayFormat.format(date);
String[] timedivided = gottime.split(":");
String gothr = timedivided[0];
long gotlong = TimeUnit.HOURS.toMinutes(Long.parseLong(gothr));
String gotmin = timedivided[1];
int gotintmin = Integer.parseInt(gotmin);
addgottime = gotlong + gotintmin;
long subtime = addgottime - addedmin;
String submilli = String.valueOf(subtime);
long submillitimeunit = TimeUnit.MINUTES.toMillis(Long.parseLong(submilli));
final int gotflippingtime = (int) submillitimeunit;
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
back_home.setEnabled(true);
} else {
fliper.showNext();
handler.postDelayed(run, gotflippingtime);
}
}
};
for (int gotinterval : gotintervals) {
handler.postDelayed(run, gotinterval);
}
handler.postDelayed(run, gotflippingtime);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
c = Calendar.getInstance();
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
long numberlong = timegot.getLong("savedwakeuptime",0);
long millicurrenttime=TimeUnit.MINUTES.toMillis(addedmin);
long subtime = numberlong-millicurrenttime;
Log.d("Calc", String.valueOf(subtime)+" "+String.valueOf(numberlong)+" "+String.valueOf(millicurrenttime));
flippingtime = (int) subtime;
intervals = new ArrayList<Integer>();
intervals.add((int) (flippingtime * 0.20f));
intervals.add((int) (flippingtime * 0.40f));
intervals.add((int) (flippingtime * 0.60f));
intervals.add((int) (flippingtime * 0.80f));
intervals.add((int) (flippingtime * 0.90f));
intervals.add((int) (flippingtime * 0.95f));
intervals.add((int) (flippingtime * 1.00f));
intervals.add(flippingtime);
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
} else {
fliper.showNext();
handler.postDelayed(run, flippingtime);
}
}
};
for (int interval : intervals) {
handler.postDelayed(run, interval);
}
handler.postDelayed(run, flippingtime);

Unable to display out the remaining date

My program will get data from database and show it in a Listview. Now I get the date from database and compare it with my current date and count the remaining day. I successfully got the data and show it in a listview, but my remaining day code is not working. Any help will be appreciated!
List<HashMap<String,Object>> aList = newArrayList<HashMap<String,Object>>();
for (int i = 0; i<records.size(); i++) {
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("txt", records.get(i).getAssname());
hm.put("txt2", records.get(i).getAssTime());
String ez = records.get(i).getAssTime();
Calendar today = Calendar.getInstance();
//count the remain day
try {
SimpleDateFormat dd = new SimpleDateFormat("dd/M/yyyy");
Date date1= dd.parse(ez);
Date date2 = today.getTime();
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
hm.put("txt3", String.valueOf(diffDays));
} catch (Exception e1) {
}
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"txt","txt2","txt3"};
// Ids of views in listview_layout
int[] to = { R.id.assigment_name,R.id.assigment_ATime, R.id.assigment_remain};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.view_assignment_entry, from, to);
What's wrong with my code ?
You can try change
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
to
long diff = date1.getTime() - date2.getTime();
long diffDays = Math.abs(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
final long DAY_MILLIS = 24* 60 * 60*1000 ;
int Days = (int) ((date_1.getTime() - date_2.getTime())/ DAY_MILLIS );
or you can use Joda time library for Java.
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
I hope it will help you...!

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)

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

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

Categories