jquery to convert date from mm/dd/yy to yyyy-dd-mm
I'm receiving an ajax response that has a date in the format mm/dd/yy. How can I convert this to the format yyyy-mm-dd using jquery? Does j开发者_如何学Cquery have an internal function to do this?
Simple with no checking of the input (JavaScript, no jQuery):
var d = '01/25/90'; // as an example
var yy = d.substr(6,2);
var newdate = (yy < 90) ? '20' + yy : '19' + yy;
newdate += '-' + d.substr(0,2) + '-' + d.substr(3,2); //1990-01-25
That sort of thing is not what jQuery is designed to facilitate. The jQuery library is primarily about DOM manipulation, with various concessions made to code structure convenience.
What you need to do is split up the incoming address as text and either reconstruct it as a compliant JavaScript parseable date, or else just get the year, month, and day from the string and use the javascript "Date()" constructor that takes those as numeric values.This code will give you a Date from your format:
This code will give you a Date from your format:
function toDate(str) {
var rv = null;
str.replace(/^(\d\d)\/(\d\d)\/(\d\d)\$/, function(d, yy, mm, dd) {
if (!d) throw "Bad date: " + str;
yy = parseInt(yy, 10);
yy = yy < 90 ? 2000 + yy : 1900 + yy;
rv = new Date(yy, parseInt(mm, 10) - 1, parseInt(dd, 10));
return null;
});
return rv;
}
<script>
$(document).ready(function(){
$("#date").change(function(){
var $d = $(this).val();
var $yy = $d.substr(6,4);
var $dd = $d.substr(3,2);
var $mm = $d.substr(0,2);
var $newdate = $yy + '-' + $mm + '-' + $dd;
$("#date").val($newdate);
});
})
</script>
精彩评论