Seconds into readable time information I had an exercise to solve, written in German. I try to translate it:


  Write a program that takes an amount of seconds. The program than has to output the number of years, days, hours and seconds.


My Solution

public class Main {
  public static void main(String[] args) {
    final int HOUR_IN_SECONDS = 60 * 60;
    final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;
    final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365;

    int seconds = 1000000000;

    // Jahre berechnen
    int years = seconds / YEAR_IN_SECONDS;
    seconds = seconds - years * YEAR_IN_SECONDS;
    System.out.println("Jahre: " + years);

    // Tage berechnen
    int days = seconds / DAY_IN_SECONDS;
    seconds = seconds - days * DAY_IN_SECONDS;
    System.out.println("Tage: " + days);

    // Stunden berechnen
    int hours = seconds / HOUR_IN_SECONDS;
    seconds = seconds - hours * HOUR_IN_SECONDS;
    System.out.println("Stunden: " + hours);

    // Minuten berechnen
    int minutes = seconds / 60;
    seconds = seconds - minutes * 60;
    System.out.println("Minuten: " + minutes);

    // Sekunden ausgeben
    System.out.println("Sekunden: " + seconds);
  }
}


This code works, but is it also beautiful enough and easy to read?
I have some suggestion for you.

1) The naming convention of the variables HOUR_IN_SECONDS, DAY_IN_SECONDS and YEAR_IN_SECONDS is not correct, since they are not constant; missing the static keyword. I suggest that you extract them in the class level.

public static final int HOUR_IN_SECONDS = 60 * 60;
public static final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;
public static final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365;

public static void main(String[] args) {
   //[...]
}


2) I suggest that you create a method that take the number of seconds and print the result.

public static void main(String[] args) {
  int seconds = 1000000000;
  printFromSeconds(seconds);
}

private static void printFromSeconds(int seconds) {
    //[...]
}


For the rest, I think it's ok since the variable seconds is closely linked with the other components.