我正在尝试将以小时和分钟为单位的休息时间值显示到我正在完成的应用程序的UI中。我利用了另一个StackOverflow论坛来解决这个问题,到目前为止,它工作得很好,时间正在显示,但我认为数学在某些地方是错误的。
我有两个TextViews,一个以分钟为单位显示活动时间,另一个以小时和分钟为单位显示休息时间(因为休息时间通常要长得多)。休息时间本质上是24小时减去活动时间。
到目前为止,我已经将我存储的活动时间字符串转换为Int,从24小时(1440分钟)的分钟值中减去它,然后使用Duration方法将该值转换为小时和分钟( hh:MM ),这很好,UI以hh:MM显示了正确的减去的值。
我的问题是,当我试图使用一个字符串将其分成几个部分时,我的字符串是(restHours + " h" + restMinutes + " minutes"),我得到了整个restTimeInt值的小时和分钟值(例如: 23h 1430分钟)。
如何更改它,使其显示正确的分钟值(例如: 23hr 40min)?
int activeTimeValue = Integer.parseInt(activityTime); // ex: 10 mins
int day = 1440;
int restTimeInt = day - activeTimeValue; // 1430 mins
Duration d = Duration.ofMinutes(restTimeInt);
int restHours = (int) d.toHours();
int restMinutes = (int) d.toMinutes();
restTimeTV.setText(restHours + " hr" + restMinutes + " mins");发布于 2021-09-10 19:29:19
Duration.minus()和Duration.toMinutesPart()
现在你已经做好了,为什么不在Duration上全力以赴,让它为你处理所有的数学问题呢?在一些帮助下,它甚至可以解析你的分钟串。
String activityTimeStr = "10"; // Minutes
Duration activityTime = Duration.parse("PT" + activityTimeStr + "M");
Duration restTime = Duration.ofDays(1).minus(activityTime);
System.out.format("Rest time: %s%n", restTime);输出为:
休息时间: PT23H50M
所以23小时50分钟,正如预期的那样。如果您需要这些数字,例如23和50,用于格式化用户,就像deHaar所说的那样,使用Duration的toMinutesPart方法
int restHours = Math.toIntExact(restTime.toHours());
int restMinutes = restTime.toMinutesPart();
System.out.format("Rest time: %d hours %d minutes%n", restHours, restMinutes);休息时间: 23小时50分钟
https://stackoverflow.com/questions/69042699
复制相似问题