1

I have a simple textfield with the type defied to be as date which attached with a jquery datepicker(). Now i have set the dateFormat() to be dd-mm-yy. All this works fine. But as i know MySql requires date in yyyy-mm-dd. So i was just wondering if i can convert that date format either using php or javascript to enter into the database.

E.g var date = $('#order_date').val(); gives value 26-2-2012. I need to convert this into 2012-02-26.

Note: There is also a 0 being added to the month.

3 Answers 3

2

Use PHP:

$date = $_POST['date']; // e.g. 06-08-2011
$mysql_date = date('Y-m-d', strtotime($date));

or

$date = explode('-', $_POST['date']);
$mysql_date = $date[2].'-'.$date[1].'-'.$date[1];

use $mysql_date to insert into the database.

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

Comments

2

You can do in javascript by parsing the input and loading it into a Date() object, and then using the getMonth, getDate, and getFullYear functions, as follows:

        //Assume input is dd-mm-yyyy
        var dateParts = $('#order_date').val().split("-");
        var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);

        //format using getMonth(), getDate() and getFullYear() methods)
        var formattedMonth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
        var formattedDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        var output = date.getFullYear() + '-' + formattedMonth + '-' + formattedDate;

You can see more at this excellent StackOverflow post

Comments

-1

did u try date.format("yyyy-mm-dd"); ? u can also use "isoDate" in place of "yyyy-mm-dd"

and if u are using mysql u can use DATE_FORMAT(date,'%Y-%m-%d')

2 Comments

Yeah, because date is a string, not a Date object.
i figured out that u must create a format function. in that case Joe's answer will work.

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.