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.

0

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Kurenai I had to tweak your answer a little bit to make it work but in the end I had to use moment.
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).

3 Comments

I'm trying to use moment to convert date like that moment(schedule.StartTime).format('hh:mm:ss'); but i get invalid date error.
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'
How on earth is this the selected answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.