[英]how to get the number of minutes from a specific time up to the current time using java.util.Date?
所以我有這個作業,這是給定的問題:
從上午5:01到下午5:00,每分鍾收費為每分鍾75美分,從下午5:01到上午5:00每分鍾收費為90美分。
這是我的代碼:
double charge = 0;
Date date = new Date();
if(date.getHours() >= 5 && date.getHours() <= 17)
{
charge += 0.75 * date.getMinutes();
System.out.println(charge);
}
else
{
charge += 0.9 * date.getMinutes();
System.out.println(charge);
}
我的問題是date.getMinutes()僅獲取當前小時的當前分鍾,應該是從凌晨5:01到當前時間的分鍾數,否則else語句也是如此。 有什么主意嗎? 多謝!
好吧,為此你可以做
totalHours = date.getHours() - 5;
totalMinutes = (totalHours * 60) + date.getMinutes();
同樣,您可以將其編寫為另一部分。
正如已經指出的,上述方法已被棄用,這是使用Calendar
Date date = new Date();
Calendar calendar = GregorianCalendar.getInstance();
calendat.setTime(date);
if(calendar.get(Calendar.HOUR_OF_DAY) > 5 && calendar.get(Calendar.HOUR_OF_DAY) < 17)
{
int totalHours = calendar.get(Calendar.HOUR_OF_DAY) - 5;
int totalMinutes = (totalHours * 60) + calendar.get(Calendar.MINUTE);
}
else
{
totalHours = 24 - calendar.get(HOUR_OF_DAY) + 5;
totalMinutes = (totalHours * 60) - (60 - calendar.get(Calendar.MINUTE);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.