0

I get invalid date while converting this string to datetime in javascript. Please help,

<p>Click the button to display the date.</p>
<p id="demo"></p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var a="9:00 PM";
var f= new Date(a.toString());
alert(f);
}
</script>
gs11111
  • 649
  • 2
  • 17
  • 49
  • Before reinventing the wheel you might want to take a look at http://momentjs.com – Tharabas Jan 17 '14 at 14:48
  • 1
    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) – VisioN Jan 17 '14 at 14:49
  • 1
    http://jsfiddle.net/Cc69S/ – adeneo Jan 17 '14 at 14:53
  • The problem is that `9:00 PM` is not a date. It's a time only. If you try your code again and set `var a="01/17/2014 9:00 PM";` you will see your code works on valid dates. – Charlie74 Jan 17 '14 at 14:56

2 Answers2

0

The problem is that 9:00 PM is not a date. It's a time only. If you try your code again and set var a="01/17/2014 9:00 PM"; you will see your code works on valid dates.

That said, if you want today's date, plus the timestamp, you can use this code:

function myFunction()
{
  var a="9:00 PM";
  var f= new Date();
  var now = new Date();

  f = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear() + " " + a;

  alert(f);
}

This gets today's date, and appends your timestamp to the end.

CODEPEN DEMO HERE

Charlie74
  • 2,883
  • 15
  • 23
0
function myFunction(hm){    
    return new Date().toDateString()+ hm;   
}

var a= " 9:00 PM";
alert(myFunction(a))

/* returned value: (String) Fri Jan 17 2014 9:00 PM */

kennebec
  • 102,654
  • 32
  • 106
  • 127