1

I seem to have a logic error in my code. The time now is: 14:38, but my code says 18:38. I know there's a Calendar class I could use, but I want to know why this code was wrong.

Code below:

public class welcome{
  public static void main(String args[]){
    //get total milliseconds since 1970
    long total_millisec = System.currentTimeMillis();

    // compute total seconds since 1970
    long total_sec = total_millisec / 1000;

    //compute current second
    long current_sec = total_sec % 60;

    //compute total minutes since epoch
    long total_mins =  total_sec / 60;

    //compute current minute
    long current_min = total_mins % 60;

    //compute total hours
    long total_hours = total_mins / 60;

    //compute current hour
    long current_hour = total_hours % 24;

    System.out.println("Time is: "+current_hour+":"+current_min+":"
    +current_sec);

    }

 }
BattleDrum
  • 798
  • 7
  • 13

1 Answers1

1

When you perform your calculation, it's presumed that System.currentTimeMillis() returns difference in milliseconds between midnight of 1st January of 1970 (which is 1970-01-01 00:00) and current time. Try to evaluate the base date in your system and see what it'll be:

System.out.println("" + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(new java.util.Date(0)));

it might return something like 1969-12-31 19:00 and this is not the midnight.

System.currentTimeMillis() returns the same as expression:

long currentTime = new java.util.Date().getTime() - new java.util.Date(0).getTime();