0

This question answers how to convert HH:mm:ss string into a Javascript date object. The string returned from HTML time input is not always in the HH:mm:ss format. The format varies.

The answers in the linked question will not work in-case of dynamic formats.

How to create a Javascript date object from this input value which does not have a fixed format?

Yuvaraj V
  • 1,020
  • 2
  • 16
  • 28
  • Possible duplicate of [How to convert a HH:mm:ss string to to a Javascript Date object?](https://stackoverflow.com/questions/13802587/how-to-convert-a-hhmmss-string-to-to-a-javascript-date-object) and [Converting time string into Date object](https://stackoverflow.com/questions/37466777) and [Javascript Date Object from string in form 'HH-MM'](https://stackoverflow.com/questions/4332906) – adiga May 21 '19 at 03:27
  • possible duplicate of [how-to-convert-html5-input-type-date-and-time-to-javascript-datetime](https://stackoverflow.com/questions/23640351/how-to-convert-html5-input-type-date-and-time-to-javascript-datetime) – AsukaSong May 21 '19 at 03:28
  • 1
    @adiga The answers in the linked question will not work in-case of dynamic formats. – Yuvaraj V May 21 '19 at 03:49

3 Answers3

12

This is an optimised version of benihamalu's answer.

const today = new Date();
console.log(new Date(today.toDateString() + ' ' + "13:30"));
Kols
  • 3,641
  • 2
  • 34
  • 42
2

I assume you want current date, in that case you need to get the current date and then pass the current time.

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
console.log(new Date(today + " " + "13:30" /*pass your time*/));
benihamalu
  • 21
  • 4
1

simple answer

function TimeToDate(time) {
    var today = new Date();
    time = new Date('1970-01-01' + ' ' + time + 'Z').getTime();
    var date = today.setHours(0, 0, 0, 0);
    var DateTime = new Date(date + time);
    return DateTime;
}

console.log(TimeToDate("13:30:7.026"));
Mn Mm
  • 26
  • 2