Java – How to convert nanosecond uptime to a readable datetime format

How to convert nanosecond uptime to a readable datetime format… here is a solution to the problem.

How to convert nanosecond uptime to a readable datetime format

I extracted accelerometer data from an Android wearable. While looking at the data, I realized that timestamps are not unix overridable. After researching, I found that the timestamp is actually nanoseconds of uptime. My problem is related to Accelerometer SensorEvent timestamp Same. But since I don’t know Java, I don’t know how to convert it using the solutions provided. Is there any Python method to convert nanoseconds in uptime to a readable datetime format? An example of a timestamp is “45900482044637”.


tl; dr

Duration.ofNanos ( 45_900_482_044_637L )



Java 8 and later have a Duration for this class, as new part of java.time frameworks (see Tutorial )。 These new classes have nanosecond resolution (nine decimal places). Duration represents the span of time in hours, minutes, and seconds.

Android does not currently use Java 8 technology, but has a back-port of java.time to Java 6 & 7. Further adaptation to Android in the ThreeTenABP project.

Note that L is appended to long's numeric literal. In addition, underlining makes lengthy numbers easier for humans to decipher.

long input = 45_900_482_044_637L;  

Let’s convert that number to a Duration object.

Duration duration = Duration.ofNanos ( input );

When we generate the string representation of the Duration object, we get a string standard formatted with ISO 8601. The standard uses the PnYnMnDTnHnMnS pattern, where P marks the beginning and T separates the year-month-day from the hour-minute-second.

    System.out.println ( "duration: " + duration );

The answer is twelve hours, forty-five minutes and one second.

duration: PT12H45M0.482044637S

Table of span-of-time classes in Java and in the ThreeTen-Extra project

About java.time

within the java.time framework in Java 8 and later. These classes replace the troublesome old classes legacy datetime classes, eg java.util.Date , Calendar , & SimpleDateFormat .

<a href=”” rel=”noreferrer noopener nofollow”>Joda-Time project, now in Maintenance mode, it is recommended to migrate to the java.time class .

To learn more, see >Oracle Tutorial Search for many examples and explanations. The specification is JSR 310

Where do I get the java.time class?

Table of which java.time library to use with which version of Java or Android

ThreeTen-Extra project extends java.time with additional classes. The project is a testing ground for future things that might be added to java.time. You may find some useful classes here, such as Interval , YearWeek , YearQuarter , and more .

Related Problems and Solutions