代码之家  ›  专栏  ›  技术社区  ›  George Udosen

如何从传递时间字符串到当前日期以毫秒为单位计时

  •  1
  • George Udosen  · 技术社区  · 8 年前

    我正试着传递一系列的表格 12:00 基于当前日期的毫秒,但我似乎无法很好地理解 Calendar Date 为达到这一目的而努力。

    现在我有了这个密码:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    
    Calendar startTime = Calendar.getInstance();
    String alarmPref = preferences.getString(PreferenceUtility.getReminderTimes(context), "12:00");
    SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.getDefault());
    Date date = format.parse(alarmPref);
    startTime.setTime(date);
    

    不幸的是,这样的日志记录给了我:

    Log.d(TAG, "Time to start:" + futureTime);
    Log.d(TAG, "Date: " + date);
    

    给出以下结果:

    07-25 14:45:21.057 8409-8409/com.google.developer.bugmaster D/PreferenceUtility:Time PreferenceUtility: 21:20
    07-25 14:45:21.057 8409-8409/com.google.developer.bugmaster D/QuizJobScheduler: Time to start:126000
    Date: Thu Jan 01 12:00:00 GMT+01:00 1970
    

    如图所示,所需字符串是 21:20 (如预期)但是 Time to start 保持价值 126000 所以我一直在找 Date: Thu Jan 01 12:00:00 GMT+01:00 1970 ,当然是指 epoch 日期和时间。

    我怎样才能得到一个参考日期和时间 21:20 以及应用程序运行的当前日期。请原谅我的无知,因为我尝试了这么多文学作品,但都没有成功,很可能我无法理解它们。

    2 回复  |  直到 8 年前
        1
  •  1
  •   user8959091user8959091    8 年前

    使用此代码:

        String time = "21:20";
        String[] splittedTime = time.split(":");
    
        Calendar calendar = Calendar.getInstance();
    
        // Set the current date and time
        calendar.setTime(new Date());
    
        // Set the desired hour and minute
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(splittedTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(splittedTime[1]));
    
        // Clear seconds and milliseconds
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    
        // the variable date will get today's date and the desired time
        Date date = calendar.getTime();
    

    我希望你能理解我在代码中的评论

        2
  •  0
  •   TEK292    8 年前

    爪哇的 Date 类不提供仅在使用当前日历日时设置时间的方法。安卓系统 Calendar 是的。

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 21);
    calendar.set(Calendar.MINUTE, 20);
    

    上面的示例要求您在不使用SimpleDateFormat的情况下解析时间。将字符串一分为二(使用“:”)并对这两个字符串进行整数分析将为您提供要放入的值。