2013-04-11 2 views
1

동적으로 생성 된 날짜를 2013 년 4 월 20 일에서 20.04.13으로 변환해야합니다. 지금까지 나는 그 달을 개종시키고 스페이서를 바꿀 수 있었다. 그러나 올해의 전환은 여전히 ​​나를 벗어납니다. 여기에 내가 지금까지 생각해 낸 것이있다. 앞으로 나아갈 방법?자바 스크립트를 사용하여 동적 4 자리 연도를 2 자리 연도로 변환

$(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; 
     } 

    } 


    }); 

    }); 

답변

7

그것은 간단한 산술입니다 :

year = year % 100; 

왜 여기

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

+0

프로그래머가 거의 날짜 형식과 같은 것을 제어 할 수 없다는 것을 잘 알고 있습니다. –

+0

고객 요구 사항 그의 친구 중 일부는 페이지가 20이없이 더 빨리로드 될 것이라고 말했습니다. 렌더러의 동적 형식을 변경하기 위해 j를 실행하면 동적 날짜가 더 느려진다는 설명에서 아무런 논의가 없었습니다. –

+0

완벽하게 작동했습니다. 감사합니다. –

1

moment.js이 정확한 문제를 해결하기위한 라이브러리입니다. 비록 당신이 그것을 사용하지 않더라도, source code는 약간 포인터를 제공 할지도 모른다.

oldDate를 Date 객체로 변환하여 거기에서 이동할 수 있습니까?

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

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

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

}); 
1
당신은 더 나은 Date 첫째로 변환 될 것

의 참조입니다 이걸하고 싶니? Y2K 문제를 기억하지 않습니까?

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); 
}); 
관련 문제