Arsman Ahmad
Arsman Ahmad

Reputation: 2221

current time in hh:mm:ss tt formate in javascript

I'm currently doing a web based task. I've got current time in this format.

hh:mm:ss

        var currentdate = new Date(); 
          var datetime = 
                 currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();

        document.write(datetime);

How can i get current time in this format:

hh:mm:ss tt

Where tt is milliseconds. [i.e., 09:46:17 89]

Upvotes: 1

Views: 1328

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

Try this by using the getMilliSeconds() method:

var currentdate = new Date(); 
          var datetime = 
                 currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds() + " "
                + Math.floor(currentdate.getMilliseconds() / 10).toFixed(0) ;

        document.write(datetime);

The Math.floor(currentdate.getMilliseconds() / 10).toFixed(0) will make sure that you are getting the millisecond in 2 digit format as expected i.e, tt

Upvotes: 0

Bhuwan Pandey
Bhuwan Pandey

Reputation: 513

Do something like this:

var date = new Date();

var milliSeconds = date.getMilliseconds();

Upvotes: 1

Mikel
Mikel

Reputation: 305

You can add milliseconds to your function, but remember, for milliseconds format must be

hh:mm:ss ttt

If you only want two units of milliseconds, you must make a rounding

var currentdate = new Date(); 
  var datetime = 
         currentdate.getHours() + ":"  
        + currentdate.getMinutes() + ":" 
        + currentdate.getSeconds() + " " 
        + currentdate.getMilliseconds();

document.write(datetime);

Upvotes: 1

Related Questions