1

How can I parse the following string :

 02/16/2015 10:51 PM

into this

 2015-02-16 22:51

The reason I want to do this is because mysql is returning an error if I try to enter the first one with the following code :

<script>

var d = Date.parse("02/16/2015 10:51 PM");
alert(d); // 1424123460000

</script>

Tried with both TIMESTAMP and DATETIME column types. Any help ?

4
  • how do you get that date string? Commented Feb 16, 2015 at 22:03
  • 1
    What's your server side language between these two layers? PHP? Commented Feb 16, 2015 at 22:03
  • 1
    Yes @War10ck it's PHP Commented Feb 16, 2015 at 22:06
  • 1
    @RafikBari your server side should be handling this, not the browser. Commented Feb 16, 2015 at 23:41

2 Answers 2

1

moment.js is a nice library that handles datetime stuff related in JS. You should try it. http://momentjs.com/

moment("any datetime string", "format of input string").format('YYYY-MM-DD HH:mm:ss');
moment("02/16/2015 10:51 PM").format("YYYY-MM-DD HH:mm:ss") // 2015-02-16 22:51:00
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. I have already tried that with moment("02/16/2015 10:51 PM").unix() but it gave me a number like 265165165 which cannot be inserted into db as well ?!
here is a jsbin using your example code - <jsbin.com/masenuwodo/1/edit?html,js,output>
0

This can be accomplished in your server side code using the strtotime() and date() functions:

$str = "02/16/2015 10:51 PM";
echo date("Y-m-d H:i", strtotime($str));

Output:

2015-02-16 22:51

With this method, you would modify the date server side before sending it to the client.

2 Comments

hi @War10ck Look like your answer makes sense. I'm passing $str through ajax? should I convert it to base64 first ? For some reason, i couldn't pass the variable as it is ?
You could try generating JSON with it (i.e echo json_encode(array("date" => date("Y-m-d H:i", strtotime($str))));). The in JavaScript you would access it like so result.date where result is the returned payload from the AJAX call.function as shown above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.