Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to turn a total number of seconds into years, months, days, minutes and seconds in Java

1 Answer

0 votes
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneOffset;

public class TimeConverter {
    public static void main(String[] args) {
        // Example input: 102,420,852 seconds
        long totalSeconds = 100_000_000L;

        // 1. Create two points in time separated by the duration
        LocalDateTime start = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC);
        LocalDateTime end = start.plusSeconds(totalSeconds);

        // 2. Use Period for years, months, and days
        Period period = Period.between(start.toLocalDate(), end.toLocalDate());

        // 3. Use Duration for hours, minutes, and seconds
        Duration duration = Duration.between(start.toLocalTime(), end.toLocalTime());
        
        // Handle negative duration cases (if time components "wrap" a day)
        if (duration.isNegative()) {
            period = period.minusDays(1);
            duration = duration.plusDays(1);
        }

        // 4. Output the results
        System.out.println("Years:   " + period.getYears());
        System.out.println("Months:  " + period.getMonths());
        System.out.println("Days:    " + period.getDays());
        System.out.println("Hours:   " + duration.toHours());
        System.out.println("Minutes: " + duration.toMinutesPart());
        System.out.println("Seconds: " + duration.toSecondsPart());
    }
}




/*
run:

Years:   3
Months:  2
Days:    2
Hours:   9
Minutes: 46
Seconds: 40

*/

 



answered Jan 21 by avibootz

Related questions

...