简体   繁体   中英

How to convert time into milliseconds?

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.

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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM