简体   繁体   中英

Converting date to this format: “X years, X months, X days…”

I am creating a Calendar instance, and setting the date to July 1, 1997 like so:

int currentYear = Calendar.getInstance().get(Calendar.YEAR); 
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(1997, 6, 1);

What I want to do, is that without using an external library, get the following output from that date (proper calculating of leap years / seconds would be good, but not required) prior to current date (eg November 1, 2015 02:45:30):

18 years, 4 months, 0 days, 2 hours, 45 minutes, 30 seconds

I am not quite sure if this is possible at all. I've tried some weird, not very logical calculations, which needed lots of improvements, but couldn't make it work:

int years = currentYear - calendar.get(Calendar.YEAR);
int months = calendar.get(Calendar.MONTH);

if(currentMonth > months) {
    years -= 1;
}

UPDATE - Code until now:

Calendar currentDate = Calendar.getInstance();
currentDate.clear();

Calendar birthDate = Calendar.getInstance();
birthDate.clear();
birthDate.set(this.birthYear, this.birthMonth - 1, this.birthDay);

Calendar date = Calendar.getInstance();
date.clear();
date.setTimeInMillis(birthDate.getTimeInMillis() - currentDate.getTimeInMillis());

System.out.println(Integer.toString(date.get(Calendar.YEAR)));

if you are using java 8 then you have LocalDateTime and PlainTimeStamp classes to use

here you find some answers Java 8: Calculate difference between two LocalDateTime

This might help

    Calendar startCalendar = Calendar.getInstance();
    startCalendar.clear();
    startCalendar.set(1997, 6, 1);
    Date start = startCalendar.getTime();

    Calendar endCalendar = Calendar.getInstance();
    // endCalendar.clear();
    // endCalendar.set(2015, 10, 1);
    Date end = endCalendar.getTime();

    long diff = end.getTime() - start.getTime();

    long days = TimeUnit.MILLISECONDS.toDays(diff);
    long hours = TimeUnit.MILLISECONDS.toHours(diff) % TimeUnit.DAYS.toHours(1);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(diff) % TimeUnit.HOURS.toMinutes(1);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(diff) % TimeUnit.MINUTES.toSeconds(1);

    System.out.println(days + " " + hours + " " + minutes + " " + seconds);

from the days we can write the logic to find the number of leap years, months using modulo division

Java 8 has a new Date API you can try that too since you're using Java 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM