我只是希望它显示从当前时间添加30分钟直到日结束前 - 今天时间是09:46 AM它应该显示像10:00AM,10:30AM,11:00AM....11:30PM
特定日期。但是在我的代码中它显示从00:00 ... 23:30一整天。这是我的代码:
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
int startDate = cal.get(Calendar.DATE);
while (cal.get(Calendar.DATE) == startDate) {
Log.d("time","currenttime"+cal.getTime());
cal.add(Calendar.MINUTE, 30);
}
Duration interval = Duration.ofMinutes(30);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
ZoneId zone = ZoneId.of("Europe/Podgorica");
ZonedDateTime now = ZonedDateTime.now(zone);
// Start at a whole half hour no earlier than now
ZonedDateTime start = now.truncatedTo(ChronoUnit.HOURS);
while (start.isBefore(now)) {
start = start.plus(interval);
}
// End when a new day begins
ZonedDateTime limit = now.toLocalDate().plusDays(1).atStartOfDay(zone);
// Iterate
ZonedDateTime currentTime = start;
while (currentTime.isBefore(limit)) {
System.out.println(currentTime.format(timeFormatter));
currentTime = currentTime.plus(interval);
}
刚刚运行代码片段时,我得到了以下输出:
20:30 21:00 21:30 22:00 22:30 23:00 23:30
当然,请替换我放置欧洲/波德戈里察的所需时区。
我使用了以下导入:
import org.threeten.bp.Duration;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;
是的,java.time
适用于较旧和较新的Android设备。它至少需要Java 6。
java.time
导入子包(不是org.threeten.bp
)。org.threeten.bp
和子包中导入日期和时间类。java.time
。使用"HH:mm"
24小时格式和"hh:mm a"
12小时格式
更新1
下面是一个完整的示例,在textview上显示您想要的内容:
TextView timeNow = findViewById(R.id.time_now);
Calendar cal, atMidnight;
//SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm a");
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
cal = Calendar.getInstance();
atMidnight = Calendar.getInstance();
atMidnight.add(Calendar.DATE, 1);
atMidnight.set(Calendar.HOUR_OF_DAY, 0);
atMidnight.set(Calendar.MINUTE, 0);
atMidnight.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, 30);
String txt = "";
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);
更新2
要将分钟数转为下一个30分钟,您可以执行以下操作:
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
int unroundedMinutes = cal.get(Calendar.MINUTE);
int mod = unroundedMinutes % 30;
cal.add(Calendar.MINUTE, 30-mod);
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);