获取时间四舍五入到最接近的5分钟间隔,并将分钟转换为字符串

时间:2015-02-10 22:32:08

标签: java

我正在看这个例子

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”)的分钟并将其转换为字符串,以便我可以在其他地方作为输入传递。

1 个答案:

答案 0 :(得分: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);