在以下代码中使用SimpleDateFormatter.format时,startDateText TextView中12:00和12:59之间的小时显示为00:00到00:59,而从13:00开始,它们正确显示为13:xx,14: xx直到23:59。
----根据要求重构代码当dtold.parse(...)中的字符串为in时,示例中的输出小时为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);
}
}
}
首先是几个像您这样的格式化程序,仅使用DateTimeFormatter
from java.time
,现代的Java日期和时间API:
private static DateTimeFormatter dtfOld = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static DateTimeFormatter dtfNew = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
需要注意的两件事:(1)按照逻辑顺序声明格式化程序,即使用顺序。在问题中使用相反的顺序使我感到困惑,我不确定是否也使自己感到困惑。(2)在00到23之间的一天中的小时中dtfOld
使用大写字母HH
,在hh
01到12的AM或PM中使用小时的小写字母(在这种情况下,相同的格式模式字母适用于SimpleDateFormat
和DateTimeFormatter
;尽管有所不同)。现在,其余的内容很无聊,只比您的代码简单:
LocalDateTime parsed = LocalDateTime.parse("2017-03-12 12:33:33", dtfOld);
System.out.println(parsed);
LocalDateTime dateTime = parsed.plusSeconds(10);
System.out.println(dateTime);
System.out.println(dateTime.format(dtfNew));
输出为:
2017-03-12T12:33:33
2017-03-12T12:33:43
12-03-2017 12:33:43
我推荐java.time
。旧的日期和时间类,您使用的- SimpleDateFormat
,Calendar
和Date
-早已过时。不仅在这种情况下,现代类还允许使用更简单的代码,这很常见。我发现java.time
工作起来通常好得多。
我已经给出了一个提示:小写hh
表示从01到12的AM或PM中的小时。当您不提供和解析AM / PM标记时,默认使用AM。而12:33:33 AM表示比午夜多半小时,并在24小时制上显示为00:33:33。
从13:00到23:59的时间?它们在AM中不存在。显然,SimpleDateFormat
它不在乎,只是从01到11的时间进行推断,因此恰好能给您所需的时间。有一个技巧可以告诉它不要;但我不想打扰,我宁愿完全不使用该类。
Oracle教程:Date Time解释如何使用java.time
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句