240

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?

4
  • 19
    @swati Because we want this to be our goto source for all our programming problems. Maybe somebody else has a better solution and this way they can all be listed as reference in one spot.
    – Alfred
    Jul 30, 2014 at 9:43
  • 34
    @swati - I know you wrote that comment over 3 years ago, but now this page is the #1 search result in Google for "get time part JavaScript". Keep in mind that today's question IS tomorrow's search results. Jul 7, 2015 at 17:03
  • 3
    @DavidDeutsch This should be like a heading in bold on the Ask question page. "today's question IS tomorrow's search results"
    – Vaulstein
    May 9, 2020 at 9:42
  • to get current time simply: new Date().toTimeString().split(' ')[0]; Mar 27 at 8:10

24 Answers 24

307
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
2
  • 2
    var d = new Date("2011-04-20 09:30:51.01"); alert(d.getHours()); // => 9 output NaN
    – Chinmay235
    May 11, 2015 at 6:04
  • 1
    @Chinmay235 Added T so now it's the right universal iso. BTW I only see undefined in IE. Anyway Fixed.
    – Royi Namir
    Apr 4, 2017 at 10:37
237

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
4
  • 9
    The calculation of adding and subtracting is helpful!
    – Dov Miller
    May 29, 2016 at 13:41
  • What would I need to change it to if I wanted to add 1 minute instead?
    – lets0code
    Apr 23, 2019 at 9:56
  • This prints out "... GMT+0800 (China Standard Time)" in all the browsers I've been testing.... You may say it is something about my settings, but even then, I want to only show HH:MM:SS using ONE command (if any).
    – Xerix
    Mar 16, 2021 at 3:40
  • 1
    what to do if i not require A.M or P.M in last of time . May 4, 2021 at 5:27
112

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

5
  • 3
    @gcoleman0828 I was late to the party. Thanks for the vote :)
    – DreamTeK
    Nov 21, 2014 at 9:22
  • ...Did you typo 'get' as 'set'? If not, your answer doesn't match your title and your title doesn't match the question.
    – anon
    May 15, 2015 at 14:55
  • @QPaysTaxes My answer does both. The javascript gets the time and the html shows the user how the code can be used to set the time also if required. I have updated my answer to reflect that. thanks for pointing it out.
    – DreamTeK
    May 18, 2015 at 7:20
  • the time is showing 30 minutes behind for me, if I click on Set time, it is correct but in military time . Set time should be toggle guess that doesnt work Jan 21, 2017 at 16:40
  • The toLocaleTime will have a different format depending on the browser's locale, instead you can use a fixed locale without PM/AM like fr to get a time matching html5 time format new Date().toLocaleTimeString('fr', {hour: '2-digit', minute:'2-digit'});
    – Tofandel
    Jul 20, 2020 at 16:04
35

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" }));

1
  • 6
    One of the clean answer to the question
    – Sushin Pv
    Aug 31, 2020 at 17:03
32

Try

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

Or

new Date().toTimeString().split(" ")[0];
1
  • 2
    In the second form if you use just toString() and change the 0 to a 4 you also get just the time in the format HH:MM:SS.
    – BigMac66
    Jul 22, 2016 at 19:39
16

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

10

Do you mean:

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

Try this

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

or

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

It should work.

1
  • Quite easy and one of the good solution. Keep up the good work. Sep 5, 2022 at 6:09
7

Try this:

var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
7
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;
}
1
  • If all you need is time without seconds and you don't need the PM or AM parts, the code above should work perfectly.
    – Hamfri
    May 21, 2018 at 7:46
5

This how you can do it.

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

2
  • 1
    This is no less cryptic or any better than new Date().toTimeString().slice(0, 5). May 5, 2019 at 18:20
  • 1
    @DanDascalescu As a (primarily) Python dev I appreciate the cryptic one-liner you've provided and would not have scrolled far enough down the page to see Parmeet Singh's concise answer (to which I'm assuming you were referring). Thanks! May 20, 2020 at 15:37
4

See these Date methods ...

3

this -

var x = new Date(); 
var h = x.getHours(); 
var m = x.getMinutes(); 
var s = x.getSeconds(); 

so-

 x = date
h = hours
m = mins
s = seconds
3

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)

3
  • How is this adding anything to the existing answers? The console.log is, as you already wrote, not really part of the solution so this this doesn't provide a new solution. Jun 9, 2021 at 23:15
  • The other answers are excessively lengthy and contain deprecated techniques. My answer provides an accurate, clean answer. Thank you for your feedback.
    – meo3w
    Jun 11, 2021 at 5:26
  • This doesn't work for times with single-digit hours or minutes Jan 27, 2022 at 11:37
2

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

1
var today = new Date();  //gets current date and time
var hour = today.getHours();         
var minute = today.getMinutes();
var second = today.getSeconds();
1
  • 1
    How is this adding anything to the existing answers? The core problem was the absence of new. Feb 4, 2019 at 18:00
1

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
}
0

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))
1
  • The shortest is Date().substr(16, 5). You don't need toString(). May 5, 2019 at 18:25
0

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;
1
  • Why assume this needs to be stored in a time element? OP asked for storing in a variable, and only for the hour and minute. let time = Date().substr(16, 5) does that. May 5, 2019 at 18:29
0

This worked for me but this depends on what you get when you hit Date():

Date().slice(16,-12)
2
0

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;
0
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;
    },
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 20, 2022 at 8:22
-2

Try this:

let date = Date().slice(16,21);
console.log(date);
-3
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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.