简体   繁体   中英

Convert time into milliseconds

I got the time from the launcher and time from system...I want to compare them and make sure that the difference is not more than 100milliseconds

public void test() throws InterruptedException {
    /*
    * Get the visible time from the launcher
    */
    TextView onLauncherDisplay = (TextView) mNextUIMainActivity.findViewById(R.id.timeOfDay);
    System.out.println("Launcher time:  " + onLauncherDisplay.getText().toString());

    /*
    * Get the system time
    */
    Calendar currentSystemTime = Calendar.getInstance();
    currentSystemTime.setTime(new Date());

    Calendar currentSystemTImeInMIlliseconds = Calendar.getInstance();
    currentSystemTImeInMIlliseconds.seu
    /*
    * Convert time into 12-hour format
    */
    SimpleDateFormat date = new SimpleDateFormat("h:mm aa");

    Calendar onLauncherTime = Calendar.getInstance();
    try {
        onLauncherTime.setTime(date.parse(onLauncherDisplay.getText().toString()));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    System.out.println("System time:  " + currentSystemTime.get(Calendar.HOUR) + ":" + currentSystemTime.get(Calendar.MINUTE));

Here i am comparing the time...hours and minutes but it is not perfect. I want to convert into milliseconds and the difference should not be more than 100 milliseconds

/*
* Compare the Launcher time with the System time
*/
if ((onLauncherTime.get(Calendar.HOUR) == currentSystemTime.get(Calendar.HOUR)) || (currentSystemTime.get(Calendar.HOUR) - onLauncherTime.get(Calendar.HOUR) == 1)) {
    if (onLauncherTime.get(Calendar.MINUTE) == currentSystemTime.get(Calendar.MINUTE) || (currentSystemTime.get(Calendar.MINUTE) - onLauncherTime.get(Calendar.MINUTE) == 1)) {
        System.out.println("Launcher time matches the On-System time!");
    }
} else {
    System.out.println("Launcher time does not matches the On-System time!!");
}

The Calendar class has a method getTimeInMillis that returns the unix epoc time value for the given calendar. That said, I don't fully understand what you're doing...

Use Calendar.getTimeInMillis() :

if (currentSystemTime.getTimeInMillis() - onLauncherTime.getTimeInMillis() < 100)
   //difference is less than 100 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