【问题标题】:How to convert American date format to European如何将美国日期格式转换为欧洲日期
【发布时间】:2011-05-19 13:44:07
【问题描述】:

来自:5/19/2011

收件人:2011-05-19

当它发现它不能像5/40/2011 等那样真实时,我需要它来引发错误。有没有做得很好的库?

【问题讨论】:

标签: javascript date


【解决方案1】:

也许这不是最佳解决方案,但您可以尝试以下简单方法:

var from="5/19/2011";
var temp = from.split("/");
var to = temp[2] + "-" + temp[0] + "-" + temp[1];

【讨论】:

    【解决方案2】:

    Datejs 是一个开源日期库怎么样?具体来说:

    http://code.google.com/p/datejs/wiki/APIDocumentation#parseExact

    Date.parseExact("10/15/2004", "M/d/yyyy");  // The Date of 15-Oct-2004
    Date.parse("15-Oct-2004", "d-MMM-yyyy");    // The Date of 15-Oct-2004
    Date.parse("2004.10.15", "yyyy.MM.dd");     // The Date of 15-Oct-2004
    Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); // The Date of 15-Oct-2004
    

    返回值 {Date} 一个 Date 对象,如果字符串不能转换为 Date 则为 null。

    http://code.google.com/p/datejs/wiki/APIDocumentation#validateDay

    Date.validateDay(15, 2007, 1);  // true, 15-Feb-2007
    Date.validateDay(31, 2007, 10); // false, throws RangeError exception
    

    返回值 {Boolean} 如果在范围内则为真,否则为假。

    【讨论】:

    • 我可以对 -1 有一些反馈吗?我意识到这是一个非常古老的答案,如果有人有什么要评论的,请分享。
    【解决方案3】:

    保持简单:

    [edit] 对,你也想要支票,所以加了 fn chkDat:

    function zeroPad(n){
      return (parseInt(n,10)<10 ? '0' : '') + n;
    }
    
    var usdat = '5/19/2011'.split('/')
        ,eudat = [usdat[2],zeroPad(usdat[0]),zeroPad(usdat[1])];
    
    alert(chkDat(usdat,eudat); //=> true
    alert(eudat.join('-'));    //=> '2011-05-19'
    
    function chkDat(orig,eu){
       var eu = new Date(eu.join('/'));
       return   eu.getMonth()+1 === parseInt(orig[0],10)
             && eu.getDate() === parseInt(orig[1],10)
             && eu.getFullYear() === parseInt(orig[2],10)
       ;
    }
    

    注意您所使用的日期格式称为日历日期 (ISO 8601)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多