4

I'm using timepicker and it requires a date object. From database I'm getting a time string like "17:00:00". How can I convert a time string like "17:00:00" into date object?

Edit I have already tried the solution in question suggested by Mike C, Alex K but in that question they are converting a date string into a date object and when I try to convert time string into date I get an invalid date error.

sqlcte
  • 323
  • 2
  • 6
  • 20

2 Answers2

8

var a = "17:00"
var b = toDate(a,"h:m")
alert(b);
function toDate(dStr,format) {
 var now = new Date();
 if (format == "h:m") {
   now.setHours(dStr.substr(0,dStr.indexOf(":")));
   now.setMinutes(dStr.substr(dStr.indexOf(":")+1));
   now.setSeconds(0);
   return now;
 }else 
  return "Invalid Format";
}
Kurenai Kunai
  • 1,842
  • 2
  • 12
  • 22
  • Kurenai I had to tweak your answer a little bit to make it work but in the end I had to use moment. – sqlcte May 30 '16 at 08:34
1

To work with dates you can write your own parser or try already proven libraries like http://momentjs.com (what I would suggest to do).

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
  • I'm trying to use moment to convert date like that moment(schedule.StartTime).format('hh:mm:ss'); but i get invalid date error. – sqlcte May 26 '16 at 17:11
  • Because the format of your string is a bit specific, you have to specify parse rule e.g. `moment(schedule.StartTime, 'HH:mm:ss').format('HH:mm:ss');` assuming `schedule.StartTime ~ '17:00:00'` – Vitalii Petrychuk May 26 '16 at 19:22
  • 2
    How on earth is this the selected answer? – ataravati Sep 08 '21 at 14:37