将天数组织成年、月、日、小时的不同部分.爪哇

Organise number of days into separate sections for year, months, days, hours. Java(将天数组织成年、月、日、小时的不同部分.爪哇)
本文介绍了将天数组织成年、月、日、小时的不同部分.爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有没有办法将通过计算两个日期之间的差异来计算的天数组织到不同的部分中,例如对于 364 天,它将是:0 年、11 个月、30 天、小时、分钟等.我认为使用逻辑运算符可能像 % 和/一样工作,但由于不同的月份有不同的天数,有些年份是闰年,我不知道该怎么做.任何帮助将非常感激.我的代码:

is there a way of organising a number of days calculated by working out the difference between two dates, into different sections e.g. for 364 days it would be: 0 years, 11 months, 30 days, hours, minutes etc. I thought using logical operators may work like % and / but as different months have different amounts of days and some years are leap years i'm not sure how to do it. Any help would be much appreciated. My code:

import java.util.*;

public class CleanDate {

    public static void main(String[] args) {
        Calendar cDate = GregorianCalendar.getInstance();
        cDate.set(2011, 0, 31, 00, 00, 00);
        Date date1 = cDate.getTime();
        Date date2 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        System.out.println("Time in minutes: " + diffMinutes + " minutes.");
        System.out.println("Time in hours: " + diffHours + " hours.");
        System.out.println("Time in days: " + diffDays + " days.");
    }
}

推荐答案

你可以像这样有效地使用 Joda Time:Interval 允许获取两个日期之间的时间间隔.

You could effectively use Joda Time like this: Interval allows to get time interval between two dates.

DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears()+" years, "
period.getMonths()+" months, "+period.getWeeks()+" weeks, "+period.getDays()+", days");

这篇关于将天数组织成年、月、日、小时的不同部分.爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to implement RecyclerView with section header depending on category?(如何根据类别实现带有节标题的 RecyclerView?)
How to generate JNI header file in Eclipse(如何在 Eclipse 中生成 JNI 头文件)
Setting a custom HTTP header dynamically with Spring-WS client(使用 Spring-WS 客户端动态设置自定义 HTTP 标头)
Could you technically call the string[] anything in the main method?(从技术上讲,您可以在 main 方法中调用 string[] 吗?)
What is the proper way of setting headers in a URLConnection?(在 URLConnection 中设置标头的正确方法是什么?)
How to overwrite http-header quot;Hostquot; in a HttpURLConnection?(如何覆盖 http-header “主机在 HttpURLConnection 中?)