Java calculates the year, month, day, hour, minute and second between two times

  1. package test01;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class TimeTest {
        public static void main(String[] args) throws Exception {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse("2015-07-23 09:44:23");
            Date date2 = sdf.parse("2020-04-23 15:58:23");
            long l = date2.getTime() - date1.getTime();
            long day = l / (24 * 60 * 60 * 1000);
            long hour = (l / (60 * 60 * 1000) - day * 24);
            long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            System.out.println( day + "天" + hour + "小时" + min + "分" + s + "秒");
        }
    

    Just convert the time difference into milliseconds, and divide the total milliseconds into every day.

    Divide the total milliseconds to become hours, subtract the day to become hours

    Divide total milliseconds into minutes, subtract days into minutes, subtract hours into minutes

Guess you like

Origin blog.csdn.net/qq_44646982/article/details/111194021