I know there are many formats of example to calculate the two dates difference. I tried in a way from that one. My answer is always correct if I input the dates within a single month. If I go for finding difference more than a month it was not giving correct answer. It was always finding the difference for two dates. How can I find date difference more that 31 days or 2016-01-05 to 2015-12-13.
Date oldDate,newDate;
SimpleDateFormat dateFormat;
//editText1=2015-12-13
//editText2=2016-01-05
oldDate = dateFormat.parse(editText1.getText().toString());
newDate = dateFormat.parse(editText2.getText().toString());
oldDate=dateFormat.parse(dateFormat.format(oldDate));
newDate=dateFormat.parse(dateFormat.format(newDate));
long diff = newDate1.getDate() - oldDate1.getDate();
editText3.setText(""+(diff+1));
Convert the dates to timestamps in milliseconds, subtract one from the other, and divide the result by 86400000 (milliseconds in a day).
long oldTime, newTime;
oldTime = dateFormat.parse(editText1.getText().toString()).getTime();
newTime = dateFormat.parse(editText2.getText().toString()).getTime();
long daysDiff = Math.abs(newTime - oldTime) / DateUtils.DAY_IN_MILLIS;
Related
I want to convert a timestamp like 62207486144 to days(like 1 year 6 months 2 days 3 hours 33 minutes) in my Android App. How can I do that? I am able to get days and hours but not years or months with the following code-
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(62207486144);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(calendar.getTime());
long timestamp = 62207486144;
long days = TimeUnit.MILLISECONDS.toDays(timestamp );
timestamp -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(timestamp );
Years- divide days by 365 (or 365.25 if you want to account for leap years). Months- well, months aren't exact because months aren't the same length, but dividing by 30 is going to be about right.
Your code above is a bit odd though. The first 4 lines are doing something totally different than the last 4. The first 4 would get you data about a specific time in a timestamp- you'd use that if you wanted to figure out for a timestamp what day/month/year it was. The last 4 treat it as a duration. You'd use that for figuring out how long something took. My suggestion above works for durations. If you want to know when a particular timestamp was instead, you'd just use the calendar object to tell you that.
check this out, as an easy way to convert to localDateTime.
From there, it should be way easier.
long millis = 62207486144L;
LocalDateTime date = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDateTime();
date.getDayOfMonth(); //Day
date.getMonthValue(); //Month
date.getYear(); //Year
More information here: https://howtoprogram.xyz/2017/02/11/convert-milliseconds-localdatetime-java/
I am working on an app and i need to get the difference between the actual date and a date inserted by the user, in days and in double.
Any idea on how to make this? I've tried some things but without success.
First you must decide if you want to consider the time of the day and the timezone to calculate the difference, because this can lead to different results.
Example: current date (AKA "today") is April 17th or 18th, depending on where in the world you are. Actually, depending on the time of the day, there might be 3 different "todays" in the world, at the same time. What timezone are you using to calculate the difference?
the user will enter a date: only day, month and year? Will it enter the hours? Are you using the user's device's timezone or some specific zone?
the same questions apply to the current date
Depending on the choices you make, you might get a different result.
Anyway, I'd use this lib: http://www.threeten.org/threetenbp/
or java.time classes, if available in your API level. In both API's you can use the following.
To use a date (day-month-year only) and the device's default timezone, I'd choose the LocalDate class:
// current date in device's default timezone
LocalDate now = LocalDate.now();
// some date from input values (May 10th 2018)
LocalDate dt = LocalDate.of(2018, 5, 10);
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
If you want to consider the time of the day (hours, minutes, etc), use a LocalDateTime. But in this case, ChronoUnit.DAYS considers a day has passed when the time is >= the other (ex: the difference between April 17th at 10 AM and April 18th 9:59 AM is zero days, because the time of the day didn't reach 10 AM, so it didn't complete 1 day - with LocalDate this doesn't happen because this class doesn't have time-of-the-day fields and considers only the day, month and year).
If you want to consider everything (date, time, and timezone), including Daylight Saving Time transitions, use a ZonedDateTime instead (the code is very similar, the only difference is that you can choose a timezone to work with):
// current date/time in device's default timezone
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// some date from input values (May 10th 2018, 10 AM in New York timezone)
ZonedDateTime dt = ZonedDateTime.of(2018, 5, 10, 10, 0, 0, 0, ZoneId.of("America/New_York"));
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
You can choose between the device's default timezone (ZoneId.systemDefault()) or a specific one (ZoneId.of("America/New_York")). You can check all the available timezones with ZoneId.getAvailableZoneIds().
Maybe it doesn't make sense to use current date in one timezone and user's date in another (I'd use the same for both), but that's up to you to decide.
Calendar c = Calendar.getInstance();
Calendar c2 // = what you will get from the user
long diff = c.getTimeInMillis()-c2.
double days = (double) diff/(1000*60*60*24);
that is what i have in mind.
I hope this helps
use this way
public static double getTimeDiffBetweenDate(Date startDateTime, Date finishDateTime) {
long diffInMilliseconds = finishDateTime.getTime() - startDateTime.getTime();
return TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds) / 60.0;
}
I tried a lot with different methods to find out exact solution, but I only get time difference, if I know future date but I want Next Sunday time from current time.
You can try this,
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int saturdayInMonth = calendar.get(Calendar.DAY_OF_MONTH) + (Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK));
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
saturdayInMonth, 23, 59, 59); // This time will be sunday night 23 hour 59 min and 59 seconds
Date sunday = new Date(calendar.getTimeInMillis() + 1000); //this is 1 second after that seconds that is sunday 00:00.
In Android, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes, together with ThreeTenABP (more on how to use it here). All the classes are in the org.threeten.bp package.
To get a difference between 2 dates, you could use a org.threeten.bp.ZonedDateTime, because this class takes care of Daylight Saving Time changes (and any other offset changes that might happen) and gives the correct/accurate result (if you calculate it without using a timezone, DST changes won't be considered in the calculation).
I also use org.threeten.bp.temporal.TemporalAdjusters class, which has a built-in method to find the next specified day-of-week (by using the constants in the org.threeten.bp.DayOfWeek class).
To get the difference, you can use org.threeten.bp.temporal.ChronoUnit.MILLIS to get the difference in milliseconds (and then you use this value to display in whatever format you want). Or you can use another constants available in org.threeten.bp.temporal.ChronoUnit class (such as MINUTES or HOURS, which will give the difference in minutes or hours - check the javadoc to see all units available).
Another way to get the difference is using a org.threeten.bp.Duration which will contain the number of seconds and nanoseconds between the 2 dates.
// change this to the timezone you need
ZoneId zone = ZoneId.of("Asia/Kolkata");
// get current date in the specified timezone
ZonedDateTime now = ZonedDateTime.now(zone);
// find next Sunday
ZonedDateTime nextSunday = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
// get the difference in milliseconds
long diffMillis = ChronoUnit.MILLIS.between(now, nextSunday);
// get the difference as a Duration
Duration duration = Duration.between(now, nextSunday);
Note that I used the timezone Asia/Kolkata. The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
The code above will get nextSunday with the same time (hour/minute/second/nanosecond) as now - except when there's a DST change (in this case, the time is adjusted accordingly).
But if you want to get the remaining time from now until the beginning of the next Sunday, then you have to adjust it to the start of the day before calculating the difference:
// adjust it to the start of the day
nextSunday = nextSunday.toLocalDate().atStartOfDay(zone);
Note that the start of a day is not always midnight - due to DST changes, a day can start at 01:00 AM for example (clocks might be set to 1 hour forward at midnight, making the first hour of the day to be 1 AM). Using atStartOfDay(zone) guarantees that you don't have to worry about that, as the API handles it for you.
If the current date is already a Sunday, what's the result you want?
The code above will get the next Sunday, even if the current date is a Sunday. If you don't want that, you can use TemporalAdjusters.nextOrSame, which returns the same date if it's already a Sunday.
To display the Duration value in time-units (like hours, minutes and seconds), you can do the following:
StringBuilder sb = new StringBuilder();
long seconds = duration.getSeconds();
long hours = seconds / 3600;
append(sb, hours, "hour");
seconds -= (hours * 3600);
long minutes = seconds / 60;
append(sb, minutes, "minute");
seconds -= (minutes * 60);
append(sb, seconds, "second");
append(sb, duration.getNano(), "nanosecond");
System.out.println(sb.toString());
// auxiliary method
public void append(StringBuilder sb, long value, String text) {
if (value > 0) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(value).append(" ");
sb.append(text);
if (value > 1) {
sb.append("s"); // append "s" for plural
}
}
}
The result (in my current time) is:
47 hours 44 minutes 43 seconds 148000000 nanoseconds
If you want the milliseconds instead of nanoseconds, you could replace append(sb, duration.getNano(), "nanosecond") with:
// get milliseconds from getNano() value
append(sb, duration.getNano() / 1000000, "millisecond");
For an easteregg in my Android app, I have to compare the current date with a stored date - and I only need to know if it's the right month.
I know that System.currentTimeMillis() is the fastest way to get the current time but now I need to get the current month from that. I avoided String comparison for it's known flaws.
My awful implementation works but it really doesn't look correct and efficient:
if (Integer.parseInt((String) DateFormat.format("MM",System.currentTimeMillis()))==12) //xmas "easteregg"
xmasBool=true;
Is there any more elegant solution for this?
Here's a better solution:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date()); // Date's default constructor gives you current time
xmasBool = calendar.get(Calendar.MONTH) == Calendar.DECEMBER;
Calendar c = Calendar.getInstance();
int month = c.get(Calendar.MONTH);
And now you can compare the variable month with your stored month.
You can compare a day or a month or both, the whole date by formatting java.Util.Date using SimpleDateFormat.
Eg.
new SimpleDateFormat("dd").format(new java.util.Date())
gives you the "day" value. Similarly "MM" will give you the month. Use combination of those as per your requirement.
Store it in the same format and you have a common standard for comparison.
I currently work on a double value that represent the total consumed time
for example, I have a 260 that means 260 second is consumed
To display to user, I would like to format it
for example , it should be something like 0year,0month,0day,1hr,2min,30sec
But I found the SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); is not quite suit my case (seems the "h" in "hr" is conflicted with the hour symbol?)
So , how to change the HH:mm:ss to the case mentioned above?
Thanks for helping
DateFormat is useful to format dates, not an absolute value of time.
To achieve your goal, you can take a look to Formatter
Hope this sample helps you:
String total_consumed_time = String.format("%01d year, %01d month, %01d day, %01d hr, %01d min, %01d sec", time_year, time_month, time_day, time_hour, time_min, time_seg);
I didn't try that code, but I use similar workaround with an absolute time in milliseconds:
long time = 260000; // time in mseg
long time_hour = TimeUnit.MILLISECONDS.toHours(time);
time -= TimeUnit.HOURS.toMillis(time_hour);
long time_min = TimeUnit.MILLISECONDS.toMinutes(time);
time -= TimeUnit.MINUTES.toMillis(time_min);
long time_seg = TimeUnit.MILLISECONDS.toSeconds(time);
String total_time = String.format("%02d:%02d:%02d", time_hour, time_min, time_seg);
With a result of "00:04:20" (4 minutes and 20 seconds).
Accepted answer is in most cases okay for solving your problem, but gives wrong reason why not to use the class SimpleDateFormat. This format class is well suited for objects of type java.util.Date (which are kind of unix timestamps in milliseconds hence absolute value of time, NOT dates). In order to treat letters like "hr" as literals you need to escape them. Example code:
// create timestamp
java.util.Date jud = new java.util.Date(260 * 1000); // milliseconds
// create format for timestamp
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy'year',M'month',d'day',H'hr',m'min',s'sec'");
// otherwise you will get extra offset time (example: in England +1 hour DST)
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
// output: 1970year,1month,1day,0hr,4min,20sec
String formatted = sdf.format(jud);
System.out.println(formatted);
Even with the applied and tricky time zone correction in code you face the problem that you have an output for the year 1970, a point in time. Hereby you can see that SimpleDateFormat does format timestamps well (absolute values in time) but NOT durations (amount resp. length of time). This semantic problem can also not be solved by the approach to use java.util.Formatter as soon as the input increases the day limit of 86400 seconds.
Old JDK and Android don't offer a built-in solution for evaluating time differences expressed in years, months and days. Java 8 does offer (limited) support with new API (class 'Period' only for date part, not time part). External libraries like JodaTime or my own one (actually only as alpha-version) give more support. JodaTime even offers a special PeriodFormatter which is ideal for solving your problem.