簡體   English   中英

將天數(int)轉換為Java中的天,月和年(包括leap年)

[英]Converting number of days(int) into days,months and years in java (including leap year)

  1. 我使用此代碼將天數轉換為尊重的天,月和年
  2. 但是結果並不精確,因為我沒有考慮31天的leap年和month年
  3. 解決/遇到此問題的最佳方法是什么
  4. 從我的程序中輸入了field_Date1和field_Date2
  5. 持續時間= field_Date2-field_Date1
  6. 持續時間是天數(整數b)
  7. 在如果我不做轉換(但條件不精確)

     import java.util.concurrent.TimeUnit; import java.math.RoundingMode; import java.text.DecimalFormat; if (field_Date1 == null || field_Date2 == null){ return ""; } else { Date startDate = (Date)field_Date1; Date endDate = (Date)field_Date2; long duration = endDate.getTime() - startDate.getTime(); long diffInDays = TimeUnit.MILLISECONDS.toDays(duration); long diff = duration - TimeUnit.DAYS.toMillis(diffInDays); double diffToHours = TimeUnit.MILLISECONDS.toHours(diff); float hoursToDay = (float) (diffToHours / 24.0); float a =hoursToDay+diffInDays; a=Math.floor(a) int b = (int)a if(b<30) { StringBuilder sb = new StringBuilder("Day: ") sb.append(b) String c = sb.toString() c } else if(b<366) { int months = b/30 int days_out=b%30 StringBuilder p1 = new StringBuilder("Days: ") StringBuilder p2 = new StringBuilder("Months: ") StringBuilder p3 = new StringBuilder(" ") p1.append(days_out) p2.append(months) p2.append(p3) p2.append(p1) String c=p2.toString() c } else { StringBuilder p1 = new StringBuilder("Months: ") StringBuilder p2 = new StringBuilder("Years: ") StringBuilder p3 = new StringBuilder(" ") StringBuilder p4 = new StringBuilder("Days: ") int years = b/365 int days_out=b%365 if(days_out>30) { int m1 = days_out/30 int m2 = days_out%30 p2.append(years) p1.append(m1) p4.append(m2) p2.append(p3) p2.append(p1) p2.append(p3) p2.append(p4) String hj = p2.toString() return hj } else { p4.append(days_out) p2.append(years) p2.append(p3) p2.append(p4) String c=p2.toString() return c } } } 

喬達時代

嘗試使用Joda-Time 2.5:

片段將如下所示:

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date startDate = (Date)field_Date1;
Date endDate = (Date)field_Date2;
int days = Days.daysBetween( new DateTime(startDate), new DateTime(endDate) ).getDays(); 

java.time

或者可以使用java.time(Java8)中的以下方法:

public static Period between(LocalDate startDateInclusive,
                             LocalDate endDateExclusive)

這將獲得兩個日期之間的時間段,包括年,月和日的數量。

如果您希望以天為單位的兩個日期之間的差值(包括leap年在內),則java.time包 (Java 8中的新增功能)為您提供:

LocalDate firstDate = LocalDate.of(2014, Month.DECEMBER, 1);
LocalDate secondDate = LocalDate.of(2016, Month.MARCH, 12);
long days = firstDate.until(secondDate,ChronoUnit.DAYS);

給您467天。

或者,

Period period = firstDate.until(secondDate);

將為您提供一個Period對象,該對象存儲分解成年,月和日的時間,即。 而不是467天,而是1年3個月11天。 這有利於人類閱讀。 但是,如果您想要總天數,那么從Period對象中獲取該天數並不容易,因此最好選擇我給的第一個選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM