2012-06-29 64 views
0

是否有任何簡單的庫或方法來獲取特定時期的某一週(從哪個日期開始?)?使用java很容易計算特定週期的幾周

例如: 有6 weeks(variable)(從2012年7月1日開始〜2012年8月11日)。

我想把2 portions (variable)中的6周剪掉。因此,其結果將是

1) 1 July,2012 ~ 21 July, 2012 

2) 22 July,2012 ~ 11 Aug, 2012... etc 

隨着jodatime,我可以很容易地得到一定的週期之間的週數雖然。

我所知道的全部是Start Date and End Date,它們都是變量和cutoffweeks amount(例如6周或4周)。

回答

1
final LocalDate start = new LocalDate(); 
final LocalDate end3 = start.plusWeeks(3) 

它並不完全清楚自己想要什麼,但Joda-Time使得大部分東西比較容易。

我想你需要的東西,如:

public void doStruff(int cutOff){ 
    int portion = cutoff/2; 
    final LocalDate start = new LocalDate(); 
    final LocalDate end = start.plusWeeks(portion) 
} 
+0

感謝。我從你的答案中得到了一個想法,如何實現我想要的。 – kitokid

0

你可以試試這個代碼:

import java.text.DateFormat; 
import java.text.ParseException; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.GregorianCalendar; 
import java.util.TimeZone; 
    public class DateDiff { 
     public static void main(String[] args) { 
     String s1 = "06/01/2012"; 
     String s2 = "06/24/2012"; 
      DateDiff dd = new DateDiff(); 
      Date then = null, now = null; 
      DateFormat df = DateFormat.getInstance(); 
      df.setTimeZone(TimeZone.getDefault()); 

      try { 
       then = df.parse(s1 + " 12:00 PM"); 
       now = df.parse(s2 + " 12:00 PM"); 
      } catch (ParseException e) { 
       System.out.println("Couldn't parse date: " + e); 
       System.exit(1); 
      } 
      long diff = dd.getDateDiff(now, then, Calendar.WEEK_OF_YEAR); 
      System.out.println("No of weeks: " + diff); 
     } 

     long getDateDiff(Date d1, Date d2, int calUnit) { 
      if(d1.after(d2)) { // make sure d1 < d2, else swap them 
      Date temp = d1; 
      d1 = d2; 
      d2 = temp; 
      } 
      GregorianCalendar c1 = new GregorianCalendar(); 
      c1.setTime(d1); 
      GregorianCalendar c2 = new GregorianCalendar(); 
      c2.setTime(d2); 
      for(long i=1; ; i++) {   
      c1.add(calUnit, 1); // add one day, week, year, etc. 
      if(c1.after(c2)) 
       return i-1; 
      } 
     } 
    } 
+0

嘗試喬達時間 – NimChimpsky

+0

我不知道喬達框架 – UVM