Unable to display out the remaining date - java

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...!

Related

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

How to get Time ago in android? [duplicate]

I have two date like:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}
out put is :
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
Short & Sweet:
/**
* Get a diff between two dates
*
* #param oldDate the old date
* #param newDate the new date
* #return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
#ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
This works and convert to String as a Bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
It will give you difference in months
long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
System.out.println(String.format("%d months", elapsedDays/30));
Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.
String date1 = "20170717141000";
String date2 = "20170719175500";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
Duration diff = Duration.between(LocalDateTime.parse(date1, formatter),
LocalDateTime.parse(date2, formatter));
if (diff.isZero()) {
System.out.println("0m");
} else {
long days = diff.toDays();
if (days != 0) {
System.out.print("" + days + "d ");
diff = diff.minusDays(days);
}
long hours = diff.toHours();
if (hours != 0) {
System.out.print("" + hours + "h ");
diff = diff.minusHours(hours);
}
long minutes = diff.toMinutes();
if (minutes != 0) {
System.out.print("" + minutes + "m ");
diff = diff.minusMinutes(minutes);
}
long seconds = diff.getSeconds();
if (seconds != 0) {
System.out.print("" + seconds + "s ");
}
System.out.println();
}
This prints
2d 3h 45m
In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.
I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.
With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.
I use this:
send start and end date in millisecond
public int GetDifference(long start,long end){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(start);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
long t=(23-hour)*3600000+(59-min)*60000;
t=start+t;
int diff=0;
if(end>t){
diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
}
return diff;
}
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
You can download class from here: DateTimeDifference GitHub Link
Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago
Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}
Try this out.
int day = 0;
int hh = 0;
int mm = 0;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
} catch (ParseException e) {
e.printStackTrace();
}
if (mm <= 60 && hh!= 0) {
if (hh <= 60 && day != 0) {
return day + " DAYS AGO";
} else {
return hh + " HOUR AGO";
}
} else {
return mm + " MIN AGO";
}
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
it returns how many days between given two dates, where DateTime is from joda library
I arranged a little. This works great.
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
#SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
Here's the simple solution:
fun printDaysBetweenTwoDates(): Int {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val endDateInMilliSeconds = dateFormat.parse("26-02-2022")?.time ?: 0
val startDateInMilliSeconds = dateFormat.parse("18-02-2022")?.time ?: 0
return getNumberOfDaysBetweenDates(startDateInMilliSeconds, endDateInMilliSeconds)
}
private fun getNumberOfDaysBetweenDates(
startDateInMilliSeconds: Long,
endDateInMilliSeconds: Long
): Int {
val difference = (endDateInMilliSeconds - startDateInMilliSeconds) / (1000 * 60 * 60 * 24).toDouble()
val noOfDays = Math.ceil(difference)
return (noOfDays).toInt()
}
When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.
You can generalize this into a function that lets you choose the output format
private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
long restDatesinMillis = date1.getTime()-date2.getTime();
Date restdate = new Date(restDatesinMillis);
return format.format(restdate);
}
Now is a simple function call like this, difference in hours, minutes and seconds:
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = formater.parse(dateEnd);
Date date2 = formater.parse(dateInit);
String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));
txtTime.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}

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)

Need to get the time difference between the two dates in hh:mm format

I need to get the time difference between to different dates in HH:MM format.Suppose I had two dates like this
02/26/2014 09:00:00 and 02/26/2014 19:30:00
I need to get the difference in hh:mm like 09:30.
I googled and tried to find solution for this but they are giving the individual hours and minutes.
I am not allowed to use Third party libraries like Joda for this. Can anyone please point me in the right direction?
UPDATE
I tried the following code
public class DateDifferentExample {
/**
* #param args
*/
public static void main(String[] args) {
String dateStart = "02/26/2014 09:00:00";
String dateStop = "02/26/2014 19:05:00";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
System.out.println("Time difference-->"+diff);
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
int diffInDays = (int) (d2.getTime() - d1.getTime());
System.out.println("Difference--> "+diffInDays);
String difft=diffHours+":"+diffMinutes;
System.out.println("Duration Time:"+difft);
/*System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");*/
//System.out.println("Getting date diff from the other method--->"+calculateDays(d1, d2));
} catch (Exception e) {
e.printStackTrace();
}
}
/*public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}*/
public static long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
}
try this
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = df.parse("02/26/2014 09:00:00");
Date d2 = df.parse("02/26/2014 19:30:00");
long d = d2.getTime() - d1.getTime();
long hh = d / (3600 * 1000);
long mm = (d - hh * 3600 * 1000) / (60 * 1000);
System.out.printf("%02d:%02d", hh, mm);
prints
10:30
My solution:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeDiff {
public static void main(String[] args) throws ParseException {
// Setup
SimpleDateFormat dateFormat = new SimpleDateFormat(
"MM/dd/yyyy HH:mm:ss");
long second = 1000l;
long minute = 60l * second;
long hour = 60l * minute;
// parsing input
Date date1 = dateFormat.parse("02/26/2014 09:00:00");
Date date2 = dateFormat.parse("02/26/2014 19:30:00");
// calculation
long diff = date2.getTime() - date1.getTime();
// printing output
System.out.print(String.format("%02d", diff / hour));
System.out.print(":");
System.out.print(String.format("%02d", (diff % hour) / minute));
System.out.print(":");
System.out.print(String.format("%02d", (diff % minute) / second));
}
}
Keep in mind, that dates are not as easy as you could expect. There are leap seconds and all kind of weird stuff.
Parse the timestamps into a Date using SimpleDateFormat.
Calculate the difference between dateOne.getTime() and dateTwo.getTime(). The result will be the difference in milliseconds.
Use the TimeUnit instances to convert the milliseconds to hours and minutes.

Calculating difference in days between dates with vectors

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.

Categories