首页 > 解决方案 > Javascript 从 HTML 日期字符串中获取日期

问题描述

我有一个包含日期的 div,如下所示:

<div id="am-event-sub-info">
 <div> February 27, 2021 11:30 am - 1:00 pm</div>
</div>

我试图从这个字符串中提取日期然后得到日期?

标签: javascript

解决方案


我希望你不介意 2021 年 2 月 27 日是星期六……

console.log(
  new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(
    new Date(
        document.querySelector('#am-event-sub-info > div')
            .innerHTML
            .split(' - ')[0]  // only interested in the "February 27, 2021 11:30 am" part
    )
  )
);
<div id="am-event-sub-info">
 <div> February 27, 2021 11:30 am - 1:00 pm</div>
</div>

更新:在 div 中添加日期之后的“天”

var day = new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(
  new Date(
      document.querySelector('#am-event-sub-info > div')
          .innerHTML
          .split(' - ')[0]  // only interested in the "February 27, 2021 11:30 am" part
  )
);

document.querySelector('#am-event-sub-info').innerHTML += '<div class="day">'+day+'</div>';
.day { color: green; }
<div id="am-event-sub-info">
 <div> February 27, 2021 11:30 am - 1:00 pm</div>
</div>


推荐阅读