Android/Java Difference between 2 dates in days [duplicate] - java

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 12 months ago.
So I'm having some issues in trying to do this, I already tried with this code:
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
And I kinda know why this is not what I want because, the thing that I need is taking the first date that I insert in database, and I want that to be like (CURRENTDATE - TXTDATE == DAYS THAT LEFT)

Maybe try this:
public long daysBetween(Calendar startDate, Calendar endDate) {
return TimeUnit.MILLISECONDS.toDays(Math.abs(endDate.getTimeInMillis() - startDate.getTimeInMillis()));
}

Related

How to make a list of dates between two dates [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 2 years ago.
I'm trying to create a list of dates that are included between two dates. Here is how I tried to do it :
public void fillDates() {
long diffInMillis = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
for (int i=0; i <= diff; i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_MONTH)+i);
Long date = calendar.getTime().getTime();
String str = convertDate(date);
dates.add(str);
}
}
dates is a list of strings, and convertDate() is converting a long date into a string date. But I think the problem comes from the lines above, as the same day is added to the list every time.
I know other similar questions exists, but I didn't find any that really helped me... But if you have an entirely different solution for me, don't hesitate ! I'm just trying to get a list of (string) dates between two dates that are submitted by the user through Date Pickers.
You should not be using Calendar, Date or SmipleDateFormat. They're troublesome. You are better off using classes from the java.time package.
If both firstDate and secondDate are LocalDates, then it'll become much easier:
List<String> dateStrings = firstDate.datesUntil(secondDate.plusDays(1))
.map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
.collect(Collectors.toList());
Note that datesUntil exists since Java 9. For Java 8, this is a helper method instead:
public static Stream<LocalDate> datesUntil(LocalDate from, LocalDate toExclusive) {
long daysBetween = ChronoUnit.DAYS.between(from, toExclusive);
return Stream.iterate(from, t -> t.plusDays(1))
.limit(daysBetween);
}

How to operate with time/date values on Java? [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Time comparison
(12 answers)
Closed 2 years ago.
I'm working on a Java program where the user, at some point, give us as an input two times (in format String). We can assume the times are from the same day. For example in the console:
Please introduce time 1:
16:00
Please introduce time 2:
10:00
My program will capture those two time values as a String and my idea was to parse it into an object of class Date.
How could I calculate which time goes first in the course of a day?
For the previous example, I would like to print the first time that takes place on the day.
How can I properly do the following?
if (date1 <= date2) System.out.println(date1); //Suppose date1 and date2 are Date objects
else System.out.println(date2);
String firstDateString = "16:00";
String secondDateString = "10:00";
LocalTime firstLocalTime = LocalTime.parse(firstDateString, DateTimeFormatter.ofPattern("HH:mm"));
LocalTime secondLocalTime = LocalTime.parse(secondDateString, DateTimeFormatter.ofPattern("HH:mm"));
if (firstLocalTime.isAfter(secondLocalTime)) {
System.out.println(secondLocalTime);
} else {
System.out.println(firstLocalTime);
}

Why there is a difference between GregorianCalendar.getTimeInMillis() and GregorianCalendargetTimeInMillis(1970.01.01)) [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));

Getting hours,minutes, and seconds from Date? [duplicate]

This question already has answers here:
Java: getMinutes and getHours
(13 answers)
Closed 8 years ago.
I want to get the current hour,minute, and second from the Date object.
This is my code:
Date date = new Date();
int hour = date.getHours();
But I get a kind of error, the getHours() part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
From Date javadoc:
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

How to add or subtract 3 days from currentdate in java? [duplicate]

This question already has answers here:
How to add one day to a date? [duplicate]
(18 answers)
Closed 9 years ago.
I need to subtract 3 days from current date and need to store that in Date variable?
You could do this
Calender c = Calender.getInstance();
c.add(DAY_OF_MONTH,3);
c.add(DAY_OF_MONTH,-3);
Date d = c.getTime();
Pull the milliseconds-since-epoch value out, subtract three days of milliseconds from it, shove it into a new Date object.
public static final long ONE_DAY_MILLIS = 86400 * 1000;
Date now = new Date();
Date then = new Date(now.getTime() - (3 * ONE_DAY_MILLIS));

Categories

Resources