将动态创建的元素中的文本转换为其他格式

时间:2015-04-24 16:32:02

标签: javascript jquery

我如何翻译以下列格式动态创建的日期:

<h3 style="margin-top: 0px" class="departure-datetime">2015-05-04 16:00:00</h3>

更像这样的可读性:

Monday 04 May - 01:00

使用jQuery?

我理解它涉及指向departure-datetime,在链接打开时使用.on函数:

$('#search-link').click(function () {
   // code to target all the elements with the class `departure-datetime` 
   // change them to "2015-05-04 16:00:00" to "Monday 04 May - 01:00"
});

1 个答案:

答案 0 :(得分:1)

使用Date.parse()和一些相关功能,我们可以:

$('.departure-datetime').each(function () {
    var value  = $(this).text().trim().split(' '),
        date   = value[1].split(':'),
        day    = value[0].split('-'),
        days   = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
        months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

    date.pop();

    $(this).html(days[new Date(Date.parse('2015-05-04')).getDay()] +' '+day[2]+' '+ months[new Date(Date.parse(value[0])).getMonth()] + ' - ' + date[0] + ':' + date[1]);  

});

结果是:

  

周一4月4日 - 16:00