【问题标题】:Calculating months, minutes, etc. between two dates [duplicate]计算两个日期之间的月份、分钟等[重复]
【发布时间】:2015-05-02 02:43:32
【问题描述】:

m0skit0 在.Net 中。八行代码。用 Java 显示它。如果你认为你可以证明它。

Dim StartDate As Date = Now
Dim EndDate As Date = Now

EndDate = EndDate.AddSeconds(15)

Dim Months As Long = DateDiff(DateInterval.Month, StartDate, EndDate)
Dim Days As Long = DateDiff(DateInterval.Day, StartDate, EndDate)
Dim Hours As Long = DateDiff(DateInterval.Hour, StartDate, EndDate)
Dim Minutes As Long = DateDiff(DateInterval.Minute, StartDate, EndDate)
Dim Seconds As Long = DateDiff(DateInterval.Second, StartDate, EndDate)

下面的代码是错误的。以 Calendar cal2 = 开头的后半部分将在 TimerTask 中计算两次之间的差异并将其分解为月、日、小时、分钟和秒。

在顶部,我得到当前日期/时间,然后添加 15 秒。然后尝试计算差异。它似乎取决于我添加到第二个日期的时间。这几天我一直在为此苦苦挣扎。在某一时刻,除了工作时间是 4 小时之外,一切都匹配了,但我是 GMT+8,所以这没有任何意义。这就是我在时区(UTC)中添加的内容。我阅读了有关 Joda 时间的信息,但我对 Java 和 Android 仍然很陌生,并且在多次尝试安装这些库并回到纯 Java 之后。痛苦。

设计日期/时间的 Java 要么是疯子,要么是受虐狂,要么两者兼而有之。

(在 .Net 中这是 8 行代码。八行!)

Calendar cal = Calendar.getInstance();
TimeZone UTC = TimeZone.getTimeZone("UTC");
cal.setTimeZone(UTC);

int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

try {
    endDate = dateFormat.parse(String.valueOf(year) + "-" + String.valueOf(month)
            + "-" + String.valueOf(day) + " " + String.valueOf(hour)
            + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds +15));
    dateFormat.setTimeZone(UTC);

} catch (ParseException ex) {
    Log.d("ParseException", ex.toString());
}

Calendar cal2 = Calendar.getInstance();
TimeZone UTC2 = TimeZone.getTimeZone("UTC");
cal.setTimeZone(UTC2);
Date beginDate = cal.getTime();

long millis = endDate.getTime() - beginDate.getTime();

if (TimeZone.getDefault().inDaylightTime( new Date())) {
    millis += 3600000;
}

String Months = (new SimpleDateFormat("M")).format(new Date(millis));
String Days = (new SimpleDateFormat("d")).format(new Date(millis));
String Hours = (new SimpleDateFormat("h")).format(new Date(millis));
String Minutes = (new SimpleDateFormat("m")).format(new Date(millis));
String Seconds = (new SimpleDateFormat("s")).format(new Date(millis));

【问题讨论】:

    标签: java android


    【解决方案1】:

    这在没有任何额外导入的情况下有效,并且它占闰年!

    import java.util.Calendar;
    
    public class Interval {
    
        int currentYear, currentMonth, currentDay, currentHour, currentMinute, currentSecond,
            otherYear, otherMonth, otherDay, otherHour, otherMinute, otherSecond;
    
        public static void main(String[] args) {
            new Interval();
        }
    
        public Interval() {
            Calendar cal = Calendar.getInstance();
    
            //Set current date values
            currentYear = cal.get(Calendar.YEAR);
            currentMonth = cal.get(Calendar.MONTH);
            currentDay = cal.get(Calendar.DAY_OF_MONTH);
            currentHour = cal.get(Calendar.HOUR_OF_DAY); //Automatically in military time
            currentMinute = cal.get(Calendar.MINUTE);
            currentSecond = cal.get(Calendar.SECOND);
    
            //Set other date values for testing
            otherYear = 2015;//year is the same
            otherMonth = 5;//months start at 0 (0-11)
            otherDay = 1;//days start at 1
            otherHour = 19;//hours start at 0 (0-23, military time)
            otherMinute = 59;//minutes start at 0 (0-59)
            otherSecond = 0;//seconds start at 0 (0-59)
    
            int yearDifference = 0, monthDifference = 0, dayDifference = 0, hourDifference = 0,
                    minuteDifference = 0, secondDifference = 0;
    
            //Calculate Differences
            yearDifference = otherYear - currentYear;
            monthDifference = otherMonth - currentMonth;
            dayDifference = otherDay - currentDay;
            hourDifference = otherHour - currentHour;
            minuteDifference = otherMinute - currentMinute;
            secondDifference = otherSecond - currentSecond;
    
            //Determine Days in given month
            int daysInCurrentMonth = 0;
            if(currentMonth == 1) {
    
                //Check for Leap Year
                if(currentYear % 4 == 0) {
                    daysInCurrentMonth = 29;
                }
                else {
                    daysInCurrentMonth = 28;
                }
            }
            else if(currentMonth == 0 || currentMonth == 2 || currentMonth == 4 || currentMonth == 6 ||
                    currentMonth == 7 || currentMonth == 9 || currentMonth == 11) {
                daysInCurrentMonth = 31;
            }
            else {
                daysInCurrentMonth = 30;
            }
    
            //Deduct 1 from upper value if current is negative
            if(secondDifference < 0) {
                minuteDifference--;
                secondDifference += 60; 
            }
            if(minuteDifference < 0) {
                hourDifference--;
                minuteDifference += 60; 
            }
            if(hourDifference < 0) {
                dayDifference--;
                hourDifference += 24; 
            }
            if(dayDifference < 0) {
                monthDifference--;
                dayDifference += daysInCurrentMonth; 
            }
            if(monthDifference < 0) {
                yearDifference--;
                monthDifference += 12; 
            }
    
            System.out.println("Difference of " + yearDifference + " years, " + monthDifference + " months, " + dayDifference + " days, " +
                hourDifference + " hours, " + minuteDifference + " minutes, and " + secondDifference + " seconds.");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 2012-12-26
      • 2023-04-06
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多