0

I am very confused on how I can convert a given time like 9:30pm into milliseconds because I need to run a code if it is past a certain time. I already know how to get the current time in milliseconds by the following code:

long timestamp = System.currentTimeMillis();

But how would I convert 9:30pm into milliseconds? I have been researching for hours now and I can only seem to find out how to get the current time.

My application needs to check if it is 9:30pm or past and if so, run a toast message.

mmBs
  • 8,421
  • 6
  • 38
  • 46
RedShirt
  • 855
  • 2
  • 20
  • 33
  • You should use the `after` method on java.util.Date. See http://docs.oracle.com/javase/6/docs/api/java/util/Date.html – Sebastian Apr 16 '14 at 21:35

5 Answers5

1

The fastest and correct way to do it on Android is to use Calendar. You can make Calendar instance static and reuse it whenever you need it.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 9);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.AM_PM, Calendar.PM);
long timeInMillis = calendar.getTimeInMillis();
Volodymyr Lykhonis
  • 2,936
  • 2
  • 17
  • 13
1

I do not need to check time in milliseconds, you can compare current time with desired values using Calendar class:

Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
if (hour > 21 || (hour == 21 && minute >= 30)) {
    doSomeJob();
}

Note that this code will not work after a midnight.

hoaz
  • 9,883
  • 4
  • 42
  • 53
0

If you need time in milliseconds for 9:30pm today, you should use Calendar object to build date and time you need.

 // init calendar with current date and default locale
 Calendar cal = Calendar.getInstance(Locale.getDefault());
 cal.setTime(new Date());

 // set new time
 cal.set(Calendar.HOUR_OF_DAY, 21);
 cal.set(Calendar.MINUTE, 30);
 cal.set(Calendar.SECOND, 0);

 // obtain given time in ms
 long today930PMinMills = cal.getTimeInMillis();
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

No need for milliseconds if you have a decent date-time library.

You can use the Joda-Time library on Android.

DateTime dateTime = new DateTime( 2014, 1, 2, 3, 4, 5 );  // Year, month, day, hour, minute, second.
boolean isNowAfterThatDateTime = DateTime.now().isAfter( dateTime );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

Why don't you do it with a constant? You said that you need to check if is past 9;30. So convert that time to milliseconds and use it ad a constant. 21:30 = (21 * 60 + 30) * 60 * 1000 will give u the 9;30 in milliseconds to compare with the current time that u get in milliseconds

Alvaro Hernandorena
  • 610
  • 1
  • 5
  • 18