如何通过时间字符串以毫秒为单位,以当前日期为参考

时间:2018-07-25 15:26:00

标签: android datetime

我正在尝试根据当前日期将格式为12:00的字符串传递给毫秒,但是我似乎无法很好地了解CalendarDate类的工作方式为此。

现在我有了以下代码:

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 个答案:

答案 0 :(得分:1)

使用此代码:

    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();

希望您能理解代码中的注释

答案 1 :(得分:0)

Java的Date类无法提供在使用当前日历日时仅设置时间的方法。 Android的Calendar类可以。

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

以上示例要求您在没有SimpleDateFormat的情况下解析时间。将字符串分为两半(使用“:”),然后对两个字符串进行整数解析,即可得到要放入的值。