gpt4 book ai didi

java - 如果时差以秒为单位,则日期格式化程序不会反射(reflect)正确的字符串

转载 作者:行者123 更新时间:2023-12-02 01:36:07 26 4
gpt4 key购买 nike

我有一个场景,我需要以某个时间间隔保存数据包接收时间。间隔以秒或分钟为单位。 (时间间隔更短)。

这是我的简单测试类,其中我为下一个数据包提供 60 秒的间隔时间。

  public static void main(String[] args) {
Date currDate = new Date();
Date nextPointDate = new Date(currDate.getTime() + 60 * 1000);

System.out.println(currDate + " " + nextPointDate);

System.out.println(DateUtil.getFormattedDate(currDate, "yyyy-MM-dd HH:mm:ss")
+ ", " + DateUtil.getFormattedDate(nextPointDate, "yyyy-MM-dd HH:mm:ss"));
}

这是我的 Date Util 方法,在这里调用:

public static String getFormattedDate(Date date, String pattern) {
DateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}

我得到的输出如下:

Tue Mar 19 14:57:50 IST 2019  Tue Mar 19 14:58:50 IST 2019
2019-03-19 14:57:50, 2019-03-19 14:57:50

第一行输出是正确的,显示出 1 分钟的差异,但是两者的输出的第二行仍然是相同的字符串。

这背后的原因是什么?如何才能达到预期的输出?

最佳答案

哥们,你的return dateFormat.format(new Date());导致了这个问题:/

正确的实现应该是return dateFormat.format(date);

关于java - 如果时差以秒为单位,则日期格式化程序不会反射(reflect)正确的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com