简体   繁体   English

jQuery将日期从mm / dd / yy转换为yyyy-dd-mm

[英]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. 我收到的ajax响应的日期格式为mm / dd / yy。 How can I convert this to the format yyyy-mm-dd using jquery? 如何使用jquery将其转换为yyyy-mm-dd格式? Does jquery have an internal function to do this? jQuery是否具有内部功能来做到这一点?

Simple with no checking of the input (JavaScript, no jQuery): 简单,无需检查输入(JavaScript,无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. 那种事情不是jQuery旨在促进的。 The jQuery library is primarily about DOM manipulation, with various concessions made to code structure convenience. jQuery库主要是关于DOM操作的,对代码结构的便利性做出了各种让步。

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: 您需要做的是将传入地址拆分为文本,然后将其重构为兼容的JavaScript可解析日期,或者仅从字符串中获取年,月和日,然后使用javascript“ Date()”构造函数这些是数字值。此代码将为您提供日期格式的日期:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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