Search code examples
javatimemillisecondsseconds

Time in milliseconds calculation


I have two string variables for timer i.e.

String StartTimer1 = "00:00:00";
String EndTimer2 = "23:59:59";

Now , I need to calculate the time left from the present time (lets say if it is 05: 30:00) once the timer has started and time left has to be in milliseconds.


Solution

  • Here some tipps to get started:

    You can parse the String to a Java Date like this:

    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date startTimer1Date = format.parse(StartTimer1);
    

    You can get the current Date and Time like this:

    Date dateNow = new Date();
    

    And since you are working with time only (and not with date and time), you will need to manipulate the Date, Month and Year of all values to a common base, e.g. :

    Calendar c = Calendar.getInstance();
    c.setTime(dateNow);
    c.set(Calendar.YEAR, 1970);
    c.set(Calendar.DAY_OF_YEAR, 1);
    dateNow = c.getTime();