Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.
Display Current Time in Milliseconds Format
In this example, we are displaying the current time with milliseconds. Earlier I have shared a tutorial where we were displaying the whole time in milliseconds.
import java.util.Calendar; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class Example { public static void main(String[] args) { //Using Date class Date date = new Date(); //Pattern for showing milliseconds in the time "SSS" DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String stringDate = sdf.format(date); System.out.println(stringDate); //Using Calendar class Calendar cal = Calendar.getInstance(); String stringDate2 = sdf.format(cal.getTime()); System.out.println(stringDate2); } }
Output:
2017-10-20 18:57:53.382 2017-10-20 18:57:53.401
Leave a Reply