George Udosen
George Udosen

Reputation: 936

How to time in milliseconds from pass time string with reference to the current date

I am trying to pass a string of the form 12:00 into milliseconds based on the current date but I seem unable to get a good understanding of how the Calendar and Date class work to achieve this.

Now I have this code:

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

This unfortunaltely gives me when logged like this:

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

Gives the following results:

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

As seen the required string is 21:20 ( as expected ) but Time to start remains at the value 126000 and hence I keep getting the date to be Date: Thu Jan 01 12:00:00 GMT+01:00 1970, which of course is a reference to the epoch date and time.

How can I get a reference date and time that refers to the time of 21:20 and for the current date the app is running. Forgive me for my ignorance as I have tried so many literature with no success most likely I am unable to understand them.

Upvotes: 1

Views: 298

Answers (2)

user8959091
user8959091

Reputation:

Use this code:

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

I hope you understand my comments in the code

Upvotes: 1

TEK292
TEK292

Reputation: 261

Java's Date class does not provide the means to set ONLY the time while using the current calendar day. Android's Calendar class does.

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

This above example requires you to parse the time without a SimpleDateFormat. Splitting the string in half (using the ':') and integer parsing the two strings would give you the values to put in.

Upvotes: 0

Related Questions