【问题标题】:SimpleDateFormat showing minutes, seconds and milliseconds wrongSimpleDateFormat 显示分钟、秒和毫秒错误
【发布时间】:2015-04-23 15:49:24
【问题描述】:

我已经编写了这个示例程序,我想将日期转换为另一种格式。使用简单日期格式时,我看不到预期日期。

 public class TestDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SimpleDateFormat originalformat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");
        SimpleDateFormat targetformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
        try {

            //Use Simple Date Format
            Date date = originalformat.parse("2015-04-09-17.18.48.677862");
            System.out.println("Using SDF "+targetformat.format(date));

            //Use Manual Translation
            String eventTime = "2015-04-09-17.18.48.677862";
            StringBuffer timeBuffer = new StringBuffer();
            for (int i = 0; i < eventTime.length(); i++) {
                if (i == 10) {
                    timeBuffer.append(" ");
                    continue;
                } else if (i == 13 || i == 16) {
                    timeBuffer.append(":");
                    continue;
                } else {
                    timeBuffer.append(eventTime.charAt(i));
                }
            }
            timeBuffer.append("000");
            String transformedTime = timeBuffer.toString().trim();
            System.out.println("Manual Translation "+transformedTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

我看到以下输出。第一个逻辑是使用简单的日期格式,第二个是手动翻译。

Using SDF 2015-04-09 17:30:05.000862
Manual Translation 2015-04-09 17:18:48.677862000

那么如何使简单的日期格式输出与手动格式完全相同的值

【问题讨论】:

  • 您指定了 677862 毫秒,即 677 秒...如果您要指定毫秒值,则应该是 3 位数,而不是 6。

标签: java datetime simpledateformat


【解决方案1】:

根据SimpleDateFormat javadocs,值677862 被解释为毫秒,而不是微秒。那是 677 秒,862 毫秒。秒部分是11分17秒,加到17.18.48变成17.30.05

要使用 S 格式,毫秒需要 3 位数字,而不是 6 位。您需要将字符串截断为最后一个小数点后的 3 位数字。

【讨论】:

    【解决方案2】:

    看来您不能使用 6 位数字表示毫秒。你的节目有 11 分 17 秒的时间。 660 秒 = 11 分钟,您有 17 秒的休息时间。因此,它只是将您的输入从秒转换为分钟,因为它不能接受超过 3 毫秒的数字。

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2013-01-12
      • 2021-10-11
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多