I have few dates in this format: 31/08/13 and I'm getting tehm from an xls file
What I need to do is to get the previous month and to calculate the days betwen these dates. I really don't know what to do.
Here is what I have tried:
code edited*
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.setTime(row.getCell(0).getDateCellValue());
start.add(start.MONTH,-1);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
if(diffDays < 0){
System.out.println(Math.abs(diffDays));
}
DateFormat dateFormatw = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormatw.format(startDate)+" and "+
dateFormatw.format(endDate)+" is "+
diffDays+" days.");
But it seems wrong. I really can't get my mind on it as I'm so tired. I lost too many hours on this without luck.
I'm trying to get the same date but one month ago and to calculate the days, between these 2 dates endTime and startTime
Please help me!
I don't know what a ProdCalendar is, it's presumably something internal to your project. But the simple way to get the numbers of days between 2 dates, which is (I think) what you want, is this:
//First date
Date d1 = dateFormat.parse("31-10-13");
//Second date
Date d2 = dateFormat.parse("31-08-13");
//Interval:
long intervalMs = d1.getTime() - d2.getTime();
long intervalDays = intervalMs/(1000*60*60*24);
In your code, date22 is initialised just with new date() so it will be the current system time. You are comparing that (in a depracated way) to a date retrieved from the spreadsheet. I also notice that Calendar cal in this line near the start:
Calendar cal = Calendar.getInstance();
cal.setTime(row.getCell(0).getDateCellValue());
Is not used again, so appears to be redundant.
Your code is more complicated than it needs to be, so you need to step back and think about what you want to achieve. Simple code is good code.
Related
I am working on an android app to keep track of hours between signing in and out.
An employee can sign in one day and sign out the next day or within the same day.
Within the app, I have a function that should calculate the difference between two times.
But I am not getting the correct results...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mma");
Date start;
Date end;
double difference;
//Test 1
start = simpleDateFormat.parse("7:00AM");
end = simpleDateFormat.parse("3:30PM");
difference = end.getTime() - start.getTime();
Log.d("difference", String.valueOf(difference)); // 3.06E7
Log.d("Time difference", String.valueOf(((difference/1000)/60)/60));
//Prints '8.5' correct.
// Text 2
start = simpleDateFormat.parse("11:00PM");
end = simpleDateFormat.parse("7:30AM");
difference = end.getTime() - start.getTime();
Log.d("difference2", String.valueOf(difference)); // -5.58E7
Log.d("Time difference2", String.valueOf(((difference/1000)/60)/60));
//Prints '-15.5' but should print '8.5'
As you can see... the first test works correctly, yet the second test fails.
How can I resolve this issue?
Your current issue is that your are calculating the difference between two hours and these hours are technically on the same day.
You are currently calculating the time difference between (A) Day 1: 23:00 and (b) Day 1: 7:30. 7:30 is 15.5 hours before 23:00.
You will need to add your starting and ending dates.
Exemple:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date day1 = simpleDateFormat.parse("12/10/2017 23:00:00");
Date day2 = simpleDateFormat.parse("13/10/2017 07:30:00");
DateTime dt1 = new DateTime(day1);
DateTime dt2 = new DateTime(day2);
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes.");
// Should print "8 hours, 30 minutes.'
start is after end (on same day), hence a negative result; -15.5 + 24 == 8.5. A modulo 24 is in order:
difference = end.getTime() - start.getTime();
difference = difference/1000/60/60;
if (difference < 0) {
difference += 24;
}
Log.d("Time difference", String.valueOf(difference));
This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have 1 datebox (datebox1) in my GWT application, which allows users to set the date in past.
Datebox1 is set to following format (not that it probably matters):
datebox1.setFormat(new DateBox.DefaultFormat (DateTimeFormat.getFormat("EEE, MMM dd, yyyy")));
How do I programatically calculate the difference in days between the date selected in the date box and the current date.
I can't find much on the net and would appreciate a simple example.
The simplest way:
Date currentDate = new Date();
int daysBetween = CalendarUtil.getDaysBetween(myDatePicker.getValue(), currentDate);
the below code block will be useful for you
Date selectedDate = DateBox.getDatePicker().getValue();
Date currentDate= new Date();
long fromDate = selectedDate.getTime();
long toDate = currentDate.getTime();
long diffGap = toDate - fromDate;
long diffDays = diffGap / (24 * 60 * 60 * 1000);
If you know how to extract date from your textbox, you can use the following function to get the time difference between any two dates
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}
I need to show in my software the amount of days, hours and minutes that a particular event occurred.
I get a string with the value of the last event and calculating the amount of time that the event occurred.
..
lastEvent: String = lastEventOcorr (); "16.07.2013 19:20:06"
..
example:
Last event occurred: 3 Days 6 Hours 45 Minutes and 42 Seconds
or
Last event occurred: 5 Minutes 30 Seconds
..
There is a practical way to do this calculation?
I really appreciate all the help.
Thank you very much
Here are several approaches on how to parse your String into a Date instance.
Afterwards you need to calculate the difference between the parsed Date and the current date (new Date()).
Finally you can format your resulting difference according to your preferences.
I would strongly suggest simply doing System.currentTimeMillis() at the start of the event and at the end of the event.
long start = System.currentTimeMillis();
//EVENT
long stop = System.currentTimeMillis();
long difference = stop - start;
Then with a little math you can get it in a nicer format.
int seconds=(difference/1000)%60;
int minutes=(difference/(1000*60))%60;
int hours=(difference/(1000*60*60))%24;
Here is an example on how to count days, you can add hours and mins to this.
long MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
String lastEvent = "13.07.2013 10:20:06";
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Date lastEventDate = sdf.parse(lastEvent);
Date currentDate = new Date();
long timeElapsed = currentDate.getTime() - lastEventDate.getTime();
long diffInDays = timeElapsed / MILLIS_IN_DAY;
System.out.println(diffInDays);
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day,
some code will be executed.
If the date that the user chose is less than the current date , some
code will be executed.
I used this code to do so ..
Calendar start2 = Calendar.getInstance();
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
start2.set(birthYear, birthMonth, birthDay);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(birthDate);
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
birthDayChosenCalender.set(birthYear,birthMonth,birthDay);
MaxBirthDayCalender.set(currentYear, currentMonth, currentDay);
long diff = birthDayChosenCalender.getTimeInMillis() - MaxBirthDayCalender.getTimeInMillis(); //result in millis
long daysBetween = diff / (24 * 60 * 60 * 1000);
System.out.println("Days between ,,,,,,,,,,,,,,,,,,"+daysBetween);
if(MaxBirthDayCalender.before(birthDayChosenCalender) && daysBetween <= 280){
do sth }
Is there any other clean way to do that ! because this way is not working well !
The other clean way to do it is to use the Joda Time library.
Other than that, everything can be done using millis and a single calendar instance:
Calendar pickedDate = new GregorianCalendar(
picker.getYear(),
picker.getMonth(),
picker.getDayOfMonth());
long pickedTime = pickedDate.getTimeInMillis();
long now = new Date().getTime();
if (pickedTime - now <= (280 * 24 * 60 * 60 * 1000)) { // 280 days in milliseconds
// ...
}
Should cover the requirement:
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day, some code will be executed.
If the date that the user chose is less than the current date , some code will be executed.
I have to calculate the difference between to dates, I have found a way but I have this strange result, Am I missing something?
public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long result = format.parse("2012-03-25 24:00").getTime() - format.parse("2012-03-25 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
result = format.parse("2012-03-26 24:00").getTime() - format.parse("2012-03-26 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
}
This is the result:
Difference in hours: 23
Difference in hours: 24
Thanks for the advices, now I'm using the Joda libray, I have this question, when I calculate the difference in this way:
DateTime begin = new DateTime("2012-03-25T00:00+01:00");
DateTime end = new DateTime("2012-03-26T00:00+01:00");
Hours m = Hours.hoursBetween(begin, end);
If I use this way to calculate the hours I get 24 hours (because the DST is not considered I assume)
What class/calculus should I use in order to get as result the 23 hours considering the DST (I have already tried different ways but I don't get it) the Period class?
Thanks for all the help...
Chances are you happen to have picked a date where daylight saving time changed in that time zone, so the day could really have been only 23 hours long. (March 25th 2012 certainly was the DST change date for Europe, e.g. Europe/London. We don't know what your default time zone is though.)
If you set your date format to use UTC, you shouldn't see this effect. (It's somewhat odd to use 24:00 in a string representation, mind you.) It's not clear what your data is meant to represent though, or what you're trying to measure. You should work out what time zone your data is really meant to be in, if you want to work out how much time actually elapsed between those local times.
(As noted in another answer, Joda Time is a much better API in general - but you still need to know how to use it properly, and when trying to work out the actual elapsed time, you'd still have seen the same results here.)
Must place the library file like explained below.
import java.util.Date;
String dateStart = dateChooserCombo1.getText();
String dateStop =dateChooserCombo2.getText();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
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);
//System.out.print(diffDays + " days, ");
jTextField3.setText(""+diffDays);
} catch (Exception e) {
e.printStackTrace();
}