【问题标题】:JAVA : how to add extra time for timestamp [duplicate]JAVA:如何为时间戳添加额外时间[重复]
【发布时间】:2014-12-12 16:50:37
【问题描述】:

对不起,我是 java 新手,我可以知道如何在这里添加额外的时间吗?

SimpleDateFormat timestampFormat    = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
String currTimestamp  = timestampFormat.format(new Date());
System.err.println("currTimestamp=="+currTimestamp); //  2014/10/17 14:31:33

【问题讨论】:

  • new Date(System.currentTimeMillis() + 3000 * 60)
  • 提示 - 使用Calendar
  • @BasilBourque 查看标题,区分日期和时间。
  • @user3835327 (a) 因此,如果添加一天的答案是调用plusDays()(Joda-Time)或.add(Calendar.DATE, 1)(java.util.Date),则添加小时或分钟的答案可能是……(b)您的问题不清楚,因为您没有定义“额外时间”。 (c) 数百 个答案已经涵盖了 Java 中时间的加法和减法。发帖前请先搜索。或者至少看一下您发布问题时建议的问题,甚至是现在此网页右侧列出的“相关”问题。

标签: java


【解决方案1】:

您可以为此使用Calender

Calendar calendar=Calendar.getInstance(); // current time
System.out.println(calendar.getTime());
calendar.add(Calendar.MINUTE,3); // add 3 minutes to current time
System.out.println(calendar.getTime());

输出:

Fri Oct 17 12:17:13 IST 2014
Fri Oct 17 12:20:13 IST 2014

【讨论】:

  • @user3835327 使用Calendar#getTimeCalendar中提取Date,根据需要格式化结果...
【解决方案2】:

Calander 类有一些有用的方法可以做到这一点。如果您还想自己使用 Date 它,请将 3000 毫秒添加到当前时间。

String resultTime = timestampFormat.format(new Date(new Date().getTime() + 3000));

【讨论】:

  • 这在某些时间范围内可能非常危险,因为它没有考虑闰秒之类的事情。当然在短距离内,它可能不是“坏”,但它会鼓励存在更好方法的坏习惯 - 只是说......
  • @MadProgrammer 点了。明白了:)
【解决方案3】:

作为比较,使用 Java 8 的新时间 API...

LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
ldt = ldt.plusMinutes(3);
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));

或者如果你不能使用 Java 8,你可以使用 JodaTime API

SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dt = DateTime.now();
System.out.println(timestampFormat.format(dt.toDate()));
dt = dt.plusMinutes(3);
Date date = dt.toDate();
System.out.println(timestampFormat.format(dt.toDate()));

【讨论】:

    【解决方案4】:

    最好使用Calendar 类而不是使用已弃用的Date 类:

    拉一个Calendar 实例:

    Calendar c = Calendar.getInstance();
    

    3 分钟添加到日历当前时间:

    c.add(Calendar.MINUTE, 3);
    

    格式化新的日历时间:

    SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    String currTimestamp = timestampFormat.format(c.getTime());
    System.err.println("currTimestamp==" + currTimestamp);
    

    【讨论】:

    • 重复同样的答案是没有意义的。
    • 当没有类似的答案时,它被编辑了。
    • 相似的意思不一样。
    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2017-11-07
    • 2015-05-01
    • 2017-05-23
    相关资源
    最近更新 更多