Convert timestamp in milliseconds to string formatted time in Java
Try this:
Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);
See SimpleDateFormat for a description of other format strings that the class accepts.
See runnable example using input of 1200 ms.
How to convert milliseconds to hh:mm:ss format?
You were really close:
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
You were converting hours to millisseconds using minutes instead of hours.
BTW, I like your use of the TimeUnit
API :)
Here's some test code:
public static void main(String[] args) throws ParseException {
long millis = 3600000;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
}
Output:
01:00:00
I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
Still using the TimeUnit
API for all magic values, and gives exactly the same output.
Convert from Millisecond to String of Date
Good you found a solution, I just like to add an approach with Java 8 new java.time API. The old classes (Date
, Calendar
and SimpleDateFormat
) have lots of problems and design issues, and it's strongly recommended to switch to the new API if possible.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
To convert the millis value to a specific timezone, you can use the Instant
class, then use a ZoneId
to convert to a timezone, creating a ZonedDateTime
.
Then you use a DateTimeFormatter
to format it:
// convert millis value to a timezone
Instant instant = Instant.ofEpochMilli(1508206600485L);
ZonedDateTime z = instant.atZone(ZoneId.of("Australia/Sydney"));
// format it
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm dd/MM/yyyy");
System.out.println(fmt.format(z)); // 01:16 17/10/2017
The output is:
01:16 17/10/2017
Note that I used hh
for the hours. According to javadoc, this lettern represents the clock-hour-of-am-pm field (values from 1 to 12), so without the AM/PM indicator, it can be ambiguous. Maybe you want to add AM/PM field (adding the letter a
to the format pattern), or change the hours to HH
(hour-of-day, with values from 0 to 23).
Also note that the actual value of the ZonedDateTime
is 2017-10-17T13:16:40.485+11:00
(01:16 PM), because in October 17th 2017, Sydney is in Daylight Saving Time, so the actual offset is +11:00
.
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
How to convert Milliseconds to X mins, x seconds in Java?
Use the java.util.concurrent.TimeUnit
class:
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
Note: TimeUnit
is part of the Java 1.5 specification, but toMinutes
was added as of Java 1.6.
To add a leading zero for values 0-9, just do:
String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
If TimeUnit
or toMinutes
are unsupported (such as on Android before API version 9), use the following equations:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...
Convert milliseconds to date string back and forth using java 7
Your problem here is the rounding. In the first method, you are converting your timestamp (which is the number of milliseconds from 1970) into a date. You are now getting only the date, discarding hours, minutes, seconds and milliseconds and converting it back. This means that you will always have a difference of the amount you are discarding (between 0 at 00:00:00:000 and 86400000 at 23:59:59:999). To fix it, simply change your date format to include the hours with milliseconds precision.
Convert String to Date with Milliseconds
The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.
You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.
If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:
System.out.println(formatter.format(dateFormatter));
outputs 2020-08-27T10:06:07.413
How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?
You can create DateTimeFormatter with input formatted date and then convert into Instant with zone to extract epoch timestamp
String date = "2019-12-13_09:23:23.333";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS");
long mills = LocalDateTime.parse(date,formatter)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
System.out.println(mills);
Related Topics
How to Add Jradiobutton to Group in Jtable
Jdbc Connection Failed, Error: Tcp/Ip Connection to Host Failed
Odd Behavior When Java Converts Int to Byte
How to Parse a JSON and Turn Its Values into an Array
How to Make Httpurlconnection Use a Proxy
What Does Swingutilities.Invokelater Do
How to Split a Comma-Separated String
How to Make a Jframe Modal in Swing Java
How to Validate Two or More Fields in Combination
Why We Use If, Else If Instead of Multiple If Block If the Body Is a Return Statement
Filter Invoke Twice When Register as Spring Bean
Abstract Class VS Interface in Java
String Concatenation in Java - When to Use +, Stringbuilder and Concat
Explicit Casting from Super Class to Subclass
Simpledateformat Parsing Date with 'Z' Literal
Java String Remove All Non Numeric Characters But Keep the Decimal Separator