The problem is the SimpleDateFormat seems to be adding 17 hours to the actual timestamp.
This should be something really simple. I’m not sure what I’m doing wrong. I have a method that will convert a long of nanoseconds to a formatted timestamp. It’s adding 17 hours. Here’s my SSCCE
package playground;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
/**
*
* @author kentcdodds
*/
public class NanosecondsToString {
public static void main(String[] args) {
long nanoseconds = 234236402;
Timestamp ts = new Timestamp(TimeUnit.MILLISECONDS.convert(nanoseconds, TimeUnit.NANOSECONDS));
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss:SSS");
String formatted = format.format(ts);
System.out.println(formatted);
}
}
The output: 17:00:00:234
I’m in Mountain Standard Time
You have to set the timezone to
UTC.SimpleDateFormatwill convert the timestamp to a time in your current time zone by default. So it is necessary to tell it to assume it as UTC. Otherwise, you can use jodatime’s interval class.