hss
hss

Reputation: 2527

How do I get the current time only in JavaScript

How can I get the current time in JavaScript and use it in a timepicker?

I tried var x = Date() and got:

Tue May 15 2012 05:45:40 GMT-0500

But I need only current time, for example, 05:45

How can I assign this to a variable?

Upvotes: 247

Views: 645350

Answers (20)

aljgom
aljgom

Reputation: 9129

Date.toLocaleTimeString() options

The Date.toLocaleTimeString() function can receive an options parameter to format the output

Some of the available options are these

new Date().toLocaleTimeString([], { timeStyle: "full" })   // 4:43:58 AM Pacific Standard Time
new Date().toLocaleTimeString([], { timeStyle: "long" })   // 4:43:58 AM PST
new Date().toLocaleTimeString([], { timeStyle: "medium" }) // 4:43:58 AM
new Date().toLocaleTimeString([], { timeStyle: "short" })  // 4:43 AM

Or you can specify the representation of the hour, minute, and second with these values:

  • "numeric" (e.g., 1)
  • "2-digit" (e.g., 01)
new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }) 
// 04:43 AM

Or set the 12-hour time using hour12: true or false

For more details take a look at Date.toLocaleTimeString() parameters and Intl.DateTimeFormat() options

Upvotes: 4

DreamTeK
DreamTeK

Reputation: 34187

Get and set the current time efficiently using javascript

I couldn't find a solution that did exactly what I needed. I wanted clean and tiny code so I came up with this:

PURE JAVASCRIPT

function timeNow(i) {
  var d = new Date(),
    h = (d.getHours()<10?'0':'') + d.getHours(),
    m = (d.getMinutes()<10?'0':'') + d.getMinutes();
  i.value = h + ':' + m;
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />


UPDATE

There is now sufficient browser support to simply use: toLocaleTimeString

For html5 type time the format must be hh:mm.

function timeNow(i) {
  i.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />

Try it on jsfiddle

Upvotes: 116

Yahya Hosseini
Yahya Hosseini

Reputation: 7

getTime() {
      let today = new Date();
      let h = today.getHours();
      let m = today.getMinutes();
      let s = today.getSeconds();
      h = h < 10 ? "0" + h : h;
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      let time = h + ":" + m + ":" + s;
      return time;
    },

Upvotes: -1

codedbychavez
codedbychavez

Reputation: 311

Here is how I'm doing this: (Hope it helps someone) What I'm doing is validating the time that the user enters in the HTML time input is not in the past:

let inputTime = value; // from time input in html (06:29)

const splittedInputTime = inputTime.split(':');

let currentDate = new Date();
currentDate.setHours(splittedInputTime[0]);
currentDate.setMinutes(splittedInputTime[1]);

const finalInputTime = currentDate.toTimeString().split(" ")[0];

const currentTime = new Date().toTimeString().split(" ")[0];

// Returns a boolean (true/ false)
let validTime = finalInputTime >= currentTime;

Upvotes: -1

sibi mahesh
sibi mahesh

Reputation: 81

Try this

new Date().toTimeString().slice(0, 8);

or

new Date().toTimeString().split(" ")[0];

It should work.

Upvotes: 8

meo3w
meo3w

Reputation: 37

A simple way to do this in ES6, in the format you requested (hh:mm), would be this way:

const goodTime = `${new Date().getHours()}:${new Date().getMinutes()}`;

console.log(goodTime);

(Obviously, the console logging is not part of the solution)

Upvotes: 2

Omer Farad
Omer Farad

Reputation: 493

You can simply use this methods.

console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));

Upvotes: 39

user7153178
user7153178

Reputation:

Simple functions to get Date and Time separated and with compatible format with Time and Date HTML input

function formatDate(date) {
  var d         = new Date(date),
      month = '' + (d.getMonth() + 1),
      day   = '' + d.getDate(),
      year  = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}

function formatTime(date) {
        var hours   = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
        var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()

        return hours + ':' + minutes
}

Upvotes: 0

Parvez Rahaman
Parvez Rahaman

Reputation: 4387

This how you can do it.

const date = new Date();
const time = date.toTimeString().split(' ')[0].split(':');
console.log(time[0] + ':' + time[1])

Upvotes: 5

Parmeet Singh
Parmeet Singh

Reputation: 187

const date = Date().slice(16,21);
console.log(date);

Upvotes: 18

Hamfri
Hamfri

Reputation: 2219

function getCurrentTime(){
    var date = new Date();
    var hh = date.getHours();
    var mm = date.getMinutes();

    hh = hh < 10 ? '0'+hh : hh; 
    mm = mm < 10 ? '0'+mm : mm;

    curr_time = hh+':'+mm;
    return curr_time;
}

Upvotes: 7

user9720939
user9720939

Reputation: 1

var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        console.log(strTime);
        $scope.time = strTime;

        date.setDate(date.getDate()+1);
        month = '' + (date.getMonth() + 1),
        day = '' + date.getDate(1),
        year = date.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        var tomorrow = [year, month, day].join('-');
        $scope.tomorrow = tomorrow;

Upvotes: -5

mhtmalpani
mhtmalpani

Reputation: 949

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

Upvotes: -2

snir
snir

Reputation: 3127

Short and simple:

new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM

4 hours later (use milisec: sec==1000):

new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48

2 days before:

new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015

Upvotes: 245

Royi Namir
Royi Namir

Reputation: 148524

var d = new Date("2011-04-20T09:30:51.01");
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51

or

var d = new Date(); // for now
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51

Upvotes: 309

user6885321
user6885321

Reputation:

This is the shortest way.

var now = new Date().toLocaleTimeString();
console.log(now)

Here is also a way through string manipulation that was not mentioned.

var now = new Date()
console.log(now.toString().substr(16,8))

Upvotes: 0

Fernando Nogueira
Fernando Nogueira

Reputation: 1566

Try

new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");

Or

new Date().toTimeString().split(" ")[0];

Upvotes: 32

StoicFnord
StoicFnord

Reputation: 193

Try this:

var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();

Upvotes: 5

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Do you mean:

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

Upvotes: 8

Related Questions