【问题标题】:How to increment time by 1 hour如何将时间增加 1 小时
【发布时间】:2011-08-22 11:12:15
【问题描述】:

我有两个时间值。一个用于上一次登录时间,一个用于当前登录时间。 我必须将以前的登录时间增加一小时。我使用了日期格式 hh:mm:ss。 这是我的代码 sn-p。

Date previous_time, current_time;

  if(previous_time.before(current_time)){
  Log.i("Time Comparision"," true");
 }

所以不是上面提到的 if 条件,我必须在 previous_time 上增加一小时并执行 if 条件。如何做到这一点?

【问题讨论】:

    标签: java android datetime


    【解决方案1】:
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(previous_time);
       calendar.add(Calendar.HOUR, 1);
       previous_time = calendar.getTime();
       // do your comparison
    

    【讨论】:

    • 对不起,我的朋友。此代码更新小时,但它完全改变了我的日期格式。我只想要“hh:mm:ss”格式的时间。
    • @Andro_Selva - 格式化和实际操作日期是两个独立的任务。查看DateFormat 和/或SimpleDateFormat
    • 然后你可以使用 SimpleDateFormat 来获得你想要的格式。在你的情况下,"new SimpleDateFormat("hh:mm:ss").format(previous_time)",在planetjones的最后一行之后。
    • 是的,同意@Rob Hruska (+1) - 正如 JavaDoc 所指出的那样“类 Date 表示特定的时间瞬间,精度为毫秒” - 格式化它不同于执行操作,例如比较它。
    • @Andro_Selva,你想发布更多代码还是准确解释你的问题 - 当你说“它没有带来任何不同”时,我无法推断你的问题是什么
    【解决方案2】:
    previous_time.setTime(previous_time.getTime() + 60 * 60 * 1000);
    

    Date session_expiry = new Date(previous_time.getTime() + 60 * 60 * 1000);
    

    http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime%28%29

    【讨论】:

      【解决方案3】:

      请试试这个代码。

          SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
          Date date = Utils.getBookingDate(mBooking.ToTime);
          Calendar calendarAdd = Calendar.getInstance();
          calendarAdd.setTime(date);
          calendarAdd.add(Calendar.HOUR, 1);
          toTime = sdf.format(calendarAdd.getTime());
          tv_Totime.setText(toTime);
      

      当当前时间字符串在加 1 小时内生成时

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多