Home > Software design >  How to convert a timestamp to years, month, days and hours in Android?
How to convert a timestamp to years, month, days and hours in Android?

Time:02-19

I want to convert a timestamp like 62207486144 to days(like 1 year 6 months 2 days 3 hours 33 minutes) in my Android App. How can I do that? I am able to get days and hours but not years or months with the following code-

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(62207486144);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(calendar.getTime());

long timestamp = 62207486144;

long days = TimeUnit.MILLISECONDS.toDays(timestamp );

timestamp -= TimeUnit.DAYS.toMillis(days);

long hours = TimeUnit.MILLISECONDS.toHours(timestamp );
                    

CodePudding user response:

Years- divide days by 365 (or 365.25 if you want to account for leap years). Months- well, months aren't exact because months aren't the same length, but dividing by 30 is going to be about right.

Your code above is a bit odd though. The first 4 lines are doing something totally different than the last 4. The first 4 would get you data about a specific time in a timestamp- you'd use that if you wanted to figure out for a timestamp what day/month/year it was. The last 4 treat it as a duration. You'd use that for figuring out how long something took. My suggestion above works for durations. If you want to know when a particular timestamp was instead, you'd just use the calendar object to tell you that.

CodePudding user response:

check this out, as an easy way to convert to localDateTime. From there, it should be way easier.

long millis = 62207486144L;
LocalDateTime date = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDateTime();
date.getDayOfMonth(); //Day
date.getMonthValue(); //Month
date.getYear(); //Year

More information here: https://howtoprogram.xyz/2017/02/11/convert-milliseconds-localdatetime-java/

  • Related