beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Display current time in Milliseconds Format

By Chaitanya Singh | Filed Under: Java Date

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

Related Posts:

  1. Java – Display time with AM/PM
  2. Java – Add Days to a Date
  3. Java – Convert a String to a 24 hour Date/Time Format
  4. Java – SimpleDateFormat class with examples
  5. Java – Convert 24 hour format to 12 hour format and vice versa

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Date and Time

  • Java Date Time
  • Java LocalDate
  • Java LocalTime
  • Java LocalDateTime
  • Java ZonedDateTime
  • Java DateTimeFormatter
  • current date time

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap