JavaScript new Date Ordinal (st, nd, rd, th)

前端 未结 15 1973
北海茫月
北海茫月 2020-11-27 03:12

If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:

<
15条回答
  •  孤街浪徒
    2020-11-27 03:36

    A short and compact solution:

    function format(date, tmp){
      return [
        (tmp = date.getDate()) + 
          ([, 'st', 'nd', 'rd'][/1?.$/.exec(tmp)] || 'th'),
        [ 'January', 'February', 'March', 'April',
          'May', 'June', 'July', 'August',
          'September', 'October', 'November', 'December'
        ][date.getMonth()],
        date.getFullYear()
      ].join(' ')
    }
    
    
    // 14 days from today
    
    console.log('14 days from today: ' + 
      format(new Date(+new Date + 14 * 864e5)));
    
    // test formatting for all dates within a month from today
    
    var day = 864e5, today = +new Date;
    for(var i = 0; i < 32; i++) {
      console.log('Today + ' + i + ': ' + format(new Date(today + i * day)))
    }

    (The compact regex-based approach for getting the ordinal suffix appears several places around the web, original source unknown)

提交回复
热议问题