使用Javascript将动态4位数年份转换为2位数年份

时间:2013-04-11 01:56:10

标签: javascript jquery regex

我需要将动态生成的日期从2013年4月20日转换为20.04.13。到目前为止,我设法转换月份并更换垫片。但转换年份仍然让我失望。这是我到目前为止所提出的。如何前进?

$(document).ready(function() {


                $('.date').each( function() {


    var oldDate = $(this).text();

    var month;

    if( oldDate.indexOf('-') > 0 ){

        var dateSplit = oldDate.split('-');

        var year = dateSplit[2];

        if( year.length == 2){
            year = year;
        }

        switch(dateSplit[1])
        {
            case 'Jan': month = "01";
            break;
            case 'Feb': month = "02";
            break;
            case 'Mar': month = "03";
            break;
            case 'Apr': month = "04";
            break;
            case 'May': month = "05";
            break;
            case 'Jun': month = "06";
            break;
            case 'Jul': month = "07";
            break;
            case 'Aug': month = "08";
            break;
            case 'Sep': month = "09";
            break;
            case 'Oct': month = "10";
            break;
            case 'Nov': month = "11";
            break;
            case 'Dec': month = "12";
            break;
        }

        $(this).text(dateSplit[0] + '.' + month  + '.' + year);
    }
    else if( oldDate.indexOf(('/') > 0 ) ){

        var dateSplit = oldDate.split('/');

        var year = dateSplit[2];

        if( year.length == 2){
            year = year;
        }

    }


    });

  });

4 个答案:

答案 0 :(得分:7)

这是简单的算术:

year = year % 100;

但你为什么要这样做呢?你不记得Y2K的问题吗?

答案 1 :(得分:2)

"20-Apr-2013".replace(/(\d+)-(\w+)-(\d+)/,function(p,p1,p2,p3) {
  return p1+'.'+String("00"+('janfebmaraprmayjunjulaugsepoctnovdec'.indexOf(p2.toLowerCase())/3+1)).slice(-2)+'.'+p3.slice(-2);
});

答案 2 :(得分:1)

您可以尝试使用库moment.js来解决这个问题。即使你不使用它,source code也可以提供一些指示。

您可以将oldDate转换为Date对象并从那里开始吗?

var newDate = new Date(oldDate);
var month = newDate.getMonth();
var year = newDate.getFullYear().toString().substr(2, 2); //get the last 2 digits of the full year

以下是functions on a javascript date object

的参考资料

答案 3 :(得分:1)

您最好先将其转换为Date

$('.date').each(function() {

    var d = new Date($(this).text());

    $(this).text(d.getDate() + '.' + (d.getMonth() + 1) + '.'
                    + ('' + d.getFullYear()).substr(2, 2));

});