Seconds to years, months, weeks and days(calculations)

Discussion in 'Plugin Development' started by Banjer_HD, Jan 9, 2017.

Thread Status:
Not open for further replies.
  1. Hello,
    I have stored an amount of seconds, for example: 34186670(one year + one month) in a long.
    And I want to let it return 1 year and 1 month, not 1 year and 13 months... How should I do it?

    Thanks!
     
  2. Online

    timtower Administrator Administrator Moderator

    @Banjer_HD Remove the year from the months when you have it.
     
  3. Offline

    DoggyCode™

    Format it using millis, here's an util I made which you can edit to achieve what you want:
    PHP:
    public static String formatMillis(long millis) {
        return 
    String.format("%d day(s), %d hour(s), %d minutes, and %d second(s)",
                    
    TimeUnit.MILLISECONDS.toDays(millis),

                    
    TimeUnit.MILLISECONDS.toHours(millis) -
                            
    TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)),

                    
    TimeUnit.MILLISECONDS.toMinutes(millis) -
                            
    TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),

                    
    TimeUnit.MILLISECONDS.toSeconds(millis) -
                            
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
         );
    }
    Just change it to "%d year(s) and %d month(s)" and change the code.

    Or, yeh, do as @timtower said.

    PHP:
    //an example
    int years 0;
    int months 0;
    for(
    int i 026months++) {
      if(
    months 11) {
        
    years++;
        
    months 0;
      }
      
    months++;
    }

    System.out.println("26 months is " years " years and " months "months");

     
    Last edited: Jan 9, 2017
Thread Status:
Not open for further replies.

Share This Page