我只希望它从当前时间开始显示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);
}
答案 0 :(得分:1)
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
。答案 1 :(得分:0)
将"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);