简体   繁体   English

用JavaScript转换日期格式

[英]Convert date format in javascript

I have an input field that on page load looks like this: 我有一个输入字段,页面加载看起来像这样:

<input type="input" id="start_date" name="start_date" value="May 12, 2012"/>

I want the following to happen: 我希望发生以下情况:

  • When a user clicks on the field to enter a date, the format changes to YYYY-MM-DD. 用户单击该字段以输入日期时,格式将更改为YYYY-MM-DD。 (2012-05-12) (2012-05-12)
  • After a user leaves the field, the format changes back to MMM DD, YYYY (May 12, 2012). 用户离开该字段后,格式更改回MMM DD,YYYY(2012年5月12日)。
  • When the data is submitted via post, it is in the format YYYY-MM-DD (2012-05-12). 通过邮寄提交数据时,其格式为YYYY-MM-DD(2012-05-12)。

How would I accomplish this with jQuery? 我将如何使用jQuery完成此操作?

If you don't want to rely on specific frameworks/plugins, you can do this: 如果您不想依赖特定的框架/插件,则可以执行以下操作:

$("#start_date").click(function() {
    var d = new Date($(this).val());
    $(this).val(d.getFullYear() + "-"
        + String(d.getMonth() + 101).slice(-2) + "-"
        + String(d.getDate() + 100).slice(-2));
}).blur(function() {
    // Eventual format checking goes here

    var m = $(this).val().split("-"),
        d = new Date(m[0], m[1] - 1, m[2]),
        s = d.toString().split(" ");
    $(this).val(s[1] + " " + s[2] + ", " + s[3]);
});

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

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