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.

Namit
  • 1,314
  • 8
  • 20
  • 36

3 Answers3

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.

Gijs P
  • 1,325
  • 12
  • 28
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

Community
  • 1
  • 1
Joe Alfano
  • 10,149
  • 6
  • 29
  • 40
-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')

hitesh israni
  • 1,742
  • 4
  • 25
  • 48