简体   繁体   中英

converting date format using javascript

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.

Eg 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.

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.

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM