I need to output the difference between 2 dates in years, months and days.
in my code when subtract two or three days from 1 year it gives wrong output
like remaining year,month,days is 0 year / 12 month /3 days
This is what I do.
Date date = null, date1 = null;
try {
date = formatter.parse(SharedPreference.getWeddingDate(getActivity()));
date1 = formatter.parse(getCurrentTimeStamp());
targetTime = new GregorianCalendar();
targetTime.setTime(date);
currentTime = new GregorianCalendar();
currentTime.setTime(date1);
}
catch (ParseException e) {
e.printStackTrace();
}
long timeOne = date.getTime();
long timeTwo = date1.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
int year = (int) (delta / 365);
int rest = (int) (delta % 365);
int month = rest / 30;
rest = rest % 30;
Unfortunately the stuff around java.util.Calendar does not give you any support for the calculation of durations. I know three external libraries available on Android platform which can do this much better and save you some headache. Internally the calculation is not so simple as some people want to make you believe. For example timezones are involved, too.
// input
String tz = "Europe/Paris";
java.util.Date d1 = new java.util.Date(0); // or: SharedPreference.getWeddingDate(getActivity());
java.util.Date d2 = new java.util.Date();
// library Threeten-ABP (similar but not identical to Java-8)
LocalDate start = Instant.ofEpochMilli(d1.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
LocalDate end = Instant.ofEpochMilli(d2.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
Period p = Period.between(start, end);
System.out.println(p.getYears()); // 45
System.out.println(p.getMonths()); // 11
System.out.println(p.getDays()); // 3
System.out.println(p); // P45Y11M3D
// Joda-Time-Android
DateTimeZone dtz = DateTimeZone.forID(tz);
org.joda.time.LocalDate jd1 = new org.joda.time.LocalDate(d1, dtz);
org.joda.time.LocalDate jd2 = new org.joda.time.LocalDate(d2, dtz);
org.joda.time.Period jp = new org.joda.time.Period(jd1, jd2, PeriodType.yearMonthDay());
System.out.println(jp.getYears()); // 45
System.out.println(jp.getMonths()); // 11
System.out.println(jp.getDays()); // 3
System.out.println(jp); // P45Y11M3D
// my library Time4A
PlainDate date1 = TemporalType.JAVA_UTIL_DATE.translate(d1).toZonalTimestamp(tz).toDate();
PlainDate date2 = TemporalType.JAVA_UTIL_DATE.translate(d2).toZonalTimestamp(tz).toDate();
Duration<CalendarUnit> duration = Duration.inYearsMonthsDays().between(date1, date2);
System.out.println(duration.getPartialAmount(CalendarUnit.YEARS)); // 45
System.out.println(duration.getPartialAmount(CalendarUnit.MONTHS)); // 11
System.out.println(duration.getPartialAmount(CalendarUnit.DAYS)); // 3
System.out.println(duration); // P45Y11M3D
If your wedding date input is in the future then just swap start and end in between-calculations in order to avoid negative durations.
Hi i need to convert milliseconds (1437790538 its 25 july 2015) to seconds but when i trying to convert seconds then it not work i get irrelevant result.From last two days very stressed from these result.
i have use this code for doing this purpose
long duration_seconds = 1437790538;
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(duration_seconds * 1000);
calendar.add(Calendar.MILLISECOND,
tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
String resultabc = sdf.format(currenTimeZone);
long curMillis = currenTimeZone.getTime() / 1000;
// long seconds = (curMillis/ 1000) % 60;
Log.e("test", "datee1 :" + resultabc + " , " + curMillis + " , " + seconds);
getDurationBreakdown(curMillis);
calculateTime(seconds);
after i need to calculate total time of post like this
public static void calculateTime(long seconds) {
int day1 = (int) TimeUnit.SECONDS.toDays(seconds);
long hours1 = TimeUnit.SECONDS.toHours(seconds) - (day1 * 24);
long minute1 = TimeUnit.SECONDS.toMinutes(seconds)
- (TimeUnit.SECONDS.toHours(seconds) * 60);
long second1 = TimeUnit.SECONDS.toSeconds(seconds)
- (TimeUnit.SECONDS.toMinutes(seconds) * 60);
Log.e("test", "time interval ::" + "Day " + day1 + " Hour " + hours1
+ " Minute " + minute1 + " Seconds " + second1);
// int days, hours, mins, seconds, justnow;
days = (int) day1;
hours = (int) hours1;
mins = (int) minute1;
seconds = (int) second1;
System.out.println("Day " + day1 + " Hour " + hours1 + " Minute1 "
+ minute1 + " Seconds " + second1);
public static String getDurationBreakdown(long millis)
{
if(millis < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
Log.e("test", "time interval" + sb.toString());
return(sb.toString());
}
}
both methods giving wrong result.
if anybody have idea how to do this thing in correct way please help me out this problem..
thanks in advance
Your
long curMillis = currenTimeZone.getTime() / 1000;
seems misleading. .getTime() will give you the time in millis, so dividing it by 1000 you will get secs not milis...
UPDATE
As far as I understand your code you simply want to calculate the difference between a given date (represented in secs) and the actual date. For that you can just do
long myDateInSecs = 1437790538; // 25 july 2015
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(myDateInSecs * 1000);
Calendar calendarNow = Calendar.getInstance();
long diff = calendarNow.getTime() - calendar.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
...
seconds % 60
1437790538 % 60 -> 38
1437790538 is a timestamp in seconds, not in milliseconds.
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();
}
I am given a unix timestamp and I need to find the difference of seconds/min/hour by comparing with current time. I need something like:
34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago
I have tried some poor if-else styled code but it is giving wrong wierd output
String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
.get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
if (diffMSec < 3600L) { // less than one hour
if (diffMSec < 60L) { // less than one minute
quantity = diffMSec;
time = "sec ago";
} else { // greater than or equal to one minute
addition = (diffMSec % 60L) > 0 ? 1 : 0;
quantity = (diffMSec / 60L) + addition;
if (quantity > 1)
time = "mins ago";
else
time = "min ago";
}
} else { // greater than or equal to one hour
addition = (diffMSec % 3600L) > 0 ? 1 : 0;
quantity = (diffMSec / 3600L) + addition;
if (quantity > 1)
time = "hours ago";
else
time = "hour ago";
}
} else { // greater than or equal to one day
addition = (diffMSec % 86400) > 0 ? 1 : 0;
quantity = (diffMSec / 86400) + addition;
if (quantity > 1)
time = "days ago";
else
time = "1 day ago";
}
time = quantity + " " + time;
I need some working code with smarter approach or even any approach with working solution. Help me to figure it out.
I think you should use Calendar
Calendar cal = Calendar.getInstance();
String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
Calendar implements Comparable so ...
long subs = Math.abs(cal.getTimeInMillis() c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);
You can also use this link, because it seems to be a problem like yours
I am given a unix timeStamp and I need to calculate the difference between current time and the given unix timestamp like:
2 sec ago
5 mins ago
2 hours ago
3 days ago
So I have written below code:
String time = "given unix timeStamp";
Date date = new Date();
date.setTime(Long.parseLong(time) * 1000);
Calendar start = Calendar.getInstance();
start.setTime(date); // given time
Calendar end = Calendar.getInstance();
end.setTime(new Date()); // current time
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone();
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
submissionTime.setText(elapsed[0] + " years," + elapsed[1] + " months,"
+ elapsed[2] + " days," + elapsed[3] + " hours," + elapsed[4]
+ " minutes," + elapsed[5] + " seconds");
And this is the elapsed() function:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone();
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
But this is giving me wrong input. I am new in Java/Android date manipulation and some full working code will be helpful.