开发者

Java Format Detailed Difference Between Dates

开发者 https://www.devze.com 2023-01-20 02:40 出处:网络
I\'m sure this has been asked before in some other way that 开发者_Python百科I just can\'t find, so I apologize upfront for repeating if I am.

I'm sure this has been asked before in some other way that 开发者_Python百科I just can't find, so I apologize upfront for repeating if I am.

I am trying to calculate the difference between two dates and then display that difference in days, minutes, and seconds; something like "3 days 23 minutes and 59 seconds"

Very easy, I'm sure, but I'm a C# guy by practice so I'm having a hard time thinking out of the box on this one.

Thanks in advance!


There is no direct to do this with the Calendar and Date objects that are currently part of the standard Java API. You could find the number of milliseconds between the two dates and use arithmetic. This depends on your accuracy needs such as if you need to account for leap years. That would make the calculation more messy, but still doable.

The Joda-Time library offers a Period object that does exactly what you are looking to do.


Date start = new Date(2010, 10, 13);
Date end   = new Date(2010, 10, 18);

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

long diffInDays  = diffInMillis/1000/86400;
long diffInHours = (diffInMillis/1000 - 86400*diffInDays) / 3600;
long diffInMins  = (diffInMillis/1000 - 86400*diffInDays - 3600*diffInHours) / 60;
long diffInSecs  = (diffInMillis/1000 - 86400*diffInDays - 3600*diffInHours - 60*diffInMins);


This is what I did, it works for me but I'm sure it can be improved or even yet, maybe there is a hidden (for me) class that does this...

/*Imports*/

package javatest;
import java.util.Date;
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        long segundo = 1000;
        long minuto = segundo * 60;
        long hora = minuto * 60;
        long dia = hora * 24;
        long semana = dia * 7;
        long mes = dia * 30;
        long anio = mes * 12;

        long startDate = new Date().getTime();
        //startDate = startDate - (semana + hora + 30 * minuto + anio*2);
        startDate = startDate - (mes);
        long endDate = new Date().getTime();

        System.out.println("Inicio: " + new Date(startDate));
        System.out.println("Final: " + new Date(endDate));

        System.out.println(PrettifyDateDiff(endDate - startDate, true));
    }

    private static String PrettifyDateDiff(long dateDiff, boolean showDisclaimer) {
        /* Constantes utilizadas para facilitar
         * la lectura de la aplicación
         */

        long second = 1000;
        long minute = second * 60;
        long hour = minute * 60;
        long day = hour * 24;
        long week = day * 7;
        long month = day * 30;
        long year = month * 12;

        // Dividimos los milisegundos entre su equivalente de
        // las constantes de arriba para obtener el valor en la
        // escala de tiempo correspondiente.
        long minutes = dateDiff / minute;
        long hours = dateDiff / hour;
        long days = dateDiff / day;
        long weeks = dateDiff / week;
        long months = dateDiff / month;
        long years = dateDiff / year;

        String prettyDateString = "";

        if (minutes > 60) {
            prettyDateString = minutes - (hours * 60) + " minutos.";

            if (hours > 24) {
                prettyDateString = hours - (days * 24) + " horas " + prettyDateString;

                if (days > 7) {
                    prettyDateString = days - (weeks * 7) + " dias " + prettyDateString;

                    if(weeks > 4){
                        prettyDateString = weeks - (months * 4)  + " semanas " + prettyDateString;

                        if(months > 12){

                            prettyDateString = months - (years * 12) + " meses " + prettyDateString;

                            if(years > 0){
                                prettyDateString = years + " años " + prettyDateString;
                            }
                        }else{
                            prettyDateString = months  + " meses " + prettyDateString;
                        }

                    }else{
                        prettyDateString = weeks + " semanas " + prettyDateString;
                    }
                } else {
                    prettyDateString = days + " dias " + prettyDateString;
                }
            } else {
                prettyDateString = hours + " horas " + prettyDateString;
            }

        } else {
            prettyDateString = minutes + " minutos.";
        }

        if(showDisclaimer && (weeks > 0 || months > 0)){
            prettyDateString += " (Semanas de 7 dias, Meses de 30 dias).";
        }

        return prettyDateString;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消