【问题标题】:how to count the seconds in java?如何在java中计算秒数?
【发布时间】:2016-07-19 07:50:10
【问题描述】:

我试图了解如何跟踪创建对象的秒数。

我正在使用的程序模拟杂货店。

某些食物具有在一定时间后变质的特性,这一切都在称为groceryItemitem 类的子类中完成。秒数不需要打印,但会使用currentTime 字段跟踪,我不太明白如何准确计算秒数。

我可能正在考虑使用 Java.util.Timer 或 Java.util.Date 库,但我不完全了解如何将它们用于我的问题。

我对 java 不是很了解,但如果能提供任何帮助,我们将不胜感激。

【问题讨论】:

    标签: java count seconds


    【解决方案1】:

    当你创建你的对象调用时。

    Date startDate = new Date();
    

    打完电话;

    Date endDate = new Date();
    

    经过的秒数是:

    int numSeconds = (int)((endDate.getTime() - startDate.getTime()) / 1000);
    

    【讨论】:

    • @Andreas 在你发帖时看到了
    【解决方案2】:

    您可以使用long 自纪元以来的毫秒值,或java.util.Date 对象(内部使用自纪元以来的毫秒值long 值,但更易于显示/调试)。

    // Using millis
    class MyObj {
        private final long createdMillis = System.currentTimeMillis();
    
        public int getAgeInSeconds() {
            long nowMillis = System.currentTimeMillis();
            return (int)((nowMillis - this.createdMillis) / 1000);
        }
    }
    
    // Using Date
    class MyObj {
        private final Date createdDate = new java.util.Date();
    
        public int getAgeInSeconds() {
            java.util.Date now = new java.util.Date();
            return (int)((now.getTime() - this.createdDate.getTime()) / 1000);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多