【发布时间】:2018-04-07 14:33:54
【问题描述】:
在以下代码中使用 SimpleDateFormatter.format 时,12:00 到 12:59 之间的时间在 startDateText TextView 中显示为 00:00 到 00:59,而从 13:00 开始正确显示为 13:xx , 14:xx 到 23:59。
---- 按要求重构代码 当 dtold.parse(...) 中的字符串是示例时,输出时间是 00:00,当它是“13:00”时,它是正确的“13:00”
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
SimpleDateFormat dtnew = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dtold = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Calendar cal = Calendar.getInstance();
cal.setTime(dtold.parse("2017-03-12 12:33:33"));
cal.add(Calendar.SECOND, 10);
System.out.println(dtnew.format(cal.getTime()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
【问题讨论】:
-
您能否将您的代码缩减为MCVE?例如不要只使用
ZonedDateTime.now()(可以是上午或下午),而是建立一个特定的时间来产生特定的(可能是不正确的)输出并显示您期望的输出。另外,请改用System.out.println(),这样人们就可以在没有TextView的情况下重现您的问题 -
@sthor69 我认为当您执行 dtold.parse(date) 时信息会丢失。事实上,您的代码在 13:00 - 23:59 的时间内工作只是未记录的功能(或错误)
-
@Ole V.V.不,我没有使用安卓。这是一个纯java应用程序
-
@Bohemian 根据要求重构代码
-
@Ole V.V.非常感谢你。我不记得为什么我使用不同的格式(HH 和 hh),但这是@Bohemian 的问题,你是对的。由于我急于尝试解决问题,我使用 StackOverflow 作为调试器系统。我以后会注意不这样做的
标签: java simpledateformat