2015-02-10 77 views
0

我在看這個例子獲取時間四捨五入到最近的5分鐘間隔只有幾分鐘轉換爲字符串

DateTime dt = new DateTime(1385577373517L, DateTimeZone.UTC); 
// Prints 2013-11-27T18:36:13.517Z 
System.out.println(dt); 

// Prints 2013-11-27T18:36:00.000Z (Floor rounded to a minute) 
System.out.println(dt.minuteOfDay().roundFloorCopy()); 

// Prints 2013-11-27T18:30:00.000Z (Rounded to custom minute Window) 
int windowMinutes = 10; 
System.out.println(
    dt.withMinuteOfHour((dt.getMinuteOfHour()/windowMinutes) * windowMinutes) 
     .minuteOfDay().roundFloorCopy() 
    ); 

我想要做的是提取物只是被四捨五入爲最接近的10分鐘間隔一分鐘(比如說「30」)並將其轉換爲一個字符串,這樣我就可以在其他地方作爲輸入了。

+0

最近的10分鐘間隔* 36是40,你想最近的10分鐘間隔*小於或等於實際的分鐘? – mstbaum 2015-02-10 22:34:47

+0

30或40對我來說可以。 40實際上會很好 – Maalamaal 2015-02-10 22:37:04

回答

1

我猜,你可以微調您的四捨五入規則周圍:

DateTime dt = new DateTime(1385577373517L, DateTimeZone.UTC); 
    // Prints 2013-11-27T18:36:13.517Z 
    System.out.println(dt); 

    // Prints 2013-11-27T18:36:00.000Z (Floor rounded to a minute) 
    System.out.println(dt.minuteOfDay().roundFloorCopy()); 

    // Prints 2013-11-27T18:30:00.000Z (Rounded to custom minute Window) 
    int windowMinutes = 10; 
    System.out.println(
     dt.withMinuteOfHour((dt.getMinuteOfHour()/windowMinutes) * windowMinutes).minuteOfDay().roundFloorCopy() 
    );   

    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("m"); 
    String minute = DATE_FORMAT.format(dt.toDate()); 

    String minString = "" + ((int)Math.round(Integer.parseInt(minute)/10)) * 10; 

    System.out.println("Result: " + minString); 
相關問題