-3

Im getting time response value as from php

00:00:00 or 10:10:10 only time values(24 hours format)

I need to convert this as javascript date object . then only i can able to use with javascript . How can achive this?

  • possible duplicate of [What is the best way to parse a time into a Date object from user input in Javascript?](http://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas) – Matteo Tassinari Jan 05 '15 at 10:59
  • To convert it to a Date you need year, month and day, not just a time. Do you want to use the current system date as the date component? – RobG Jan 05 '15 at 11:00
  • i am storing time to mysql db and retrieve though php and list it angularjs. for this i cannot get as date from php , only getting as string . – Suresh Velusamy Jan 05 '15 at 11:07
  • i got a solution using momentjs thank you for interest on my question – Suresh Velusamy Jan 05 '15 at 11:11

2 Answers2

0

Using Moment js we can achieve

  var dateObj= moment('15:00:00', 'HH:MM:SS').toDate();
  console.log(dateObj);

Out put Mon Dec 01 2014 15:00:00 GMT+0530 (India Standard Time)

0

A JavaScript Date object requires a Date as well as a time, so you will need to provide that with your received PHP time.

I'm guessing that you'd just want to use the current Day, Month and Year, so we will:

var d     = new Date();
var year  = d.getFullYear();
var month = d.getMonth();
var day   = d.getDate();
var msecs = d.getMilliseconds();

Of course, you can also use the UTC methods instead.

Now that you have all the information necessary for a Date object, but the hours, minutes and seconds, we can create those from your PHP-provided string:

var hours = /\d\d/.exec(str);
var mins  = /(?!^)\d\d/.exec(str);
var secs  = /\d\d$/.exec(str);

Now we have everything necessary to create our Date object, we can do so:

var ourDate = new Date(year, month, day, hours, mins, secs, msecs);

Ta - da!

See a working fiddle.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119