首页 > 解决方案 > 我需要将两个日期分成不同的值

问题描述

当我使用 Apify 抓取网站时,我需要一些 JavaScript 将这样显示的两个日期08 Oct - 12 Oct 2019分隔为单独的值。10/08/201910/12/2019

我已经开始使用 Apify 从当地剧院网站上抓取一些事件数据,这样我就可以自己提供相同的信息。剧院公司将开始和结束日期写在一个段落标签中,这意味着它在一个单元格中返回两个日期。

为了让我的网站使用剧院公司的日期数据,我需要像这样格式化每个日期,mm/dd/yyyy并且需要将每个日期分成它们自己的值。javascript有没有办法将提供的示例中的日期分开并将它们格式化为美国日期形式?

例如,这是我从https://theatreroyal.com/whats-on/the-rocky-horror-show/抓取数据的页面之一

async function pageFunction(context) {
    const { request, log, jQuery } = context;

    const $ = jQuery;
    const title = $('title').text();

    log.info(`URL: ${request.url} TITLE: ${title}`);

    return {
        url: request.url,
        name: $('.c-pg-masthead-wrapper--events-fixed .c-pg-title').text(),
        date: $('.c-pg-masthead-wrapper--events-fixed .c-pg-subtitle').text().trim()
    };
}

目前,上面的脚本返回写入的日期,即10 October - 12 Oct 2019无法满足我的需要。

我真的很感激一些帮助。提前致谢!

标签: javascriptapify

解决方案


这是一个将从和返回的函数

我用了

const format = { month: '2-digit', day: '2-digit', year: 'numeric' };

const getDates = (dateStr) => {
  [_, fd, fm, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  const from = new Date(`${fd} ${fm} ${year} 15:00:00`); // using 15:00 for dst reasons
  const to   = new Date(`${td} ${tm} ${year} 15:00:00`);
  return {
    "from": from.toLocaleDateString("en-US", format),
      "to":   to.toLocaleDateString("en-US", format)
  }
};

const date = '08 Oct - 12 Oct 2019'; // change to your date string
const dates = getDates(date); // how to call it
console.log(dates.from, dates.to); // how to use the dates returned

这是一个可以处理跨年字符串的版本

const format = { month: '2-digit', day: '2-digit', year: 'numeric' };

const getDates = (dateStr) => {
  const sameYear = dateStr.split(" ").length === 6; // dd mmm - dd mmm yyyy
  let fy="";
  if (sameYear) {
    [_, fd, fm, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  }
  else {
    [_, fd, fm, fy, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) (\d{4}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  }
  const from = new Date(`${fd} ${fm} ${fy?fy:year} 15:00:00`); // using 15:00 for dst reasons
  const to   = new Date(`${td} ${tm} ${year} 15:00:00`);
  return {
    "from": from.toLocaleDateString("en-US", format),
      "to":   to.toLocaleDateString("en-US", format)
  }
};

const date1 = '08 Oct - 12 Oct 2019'; // change to your date string
const dates1 = getDates(date1); // how to call it
console.log(dates1.from, dates1.to); // how to use the dates returned

const date2 = '08 Dec 2019 - 12 Jan 2020'; // change to your date string
const dates2 = getDates(date2); // how to call it
console.log(dates2.from, dates2.to); // how to use the dates returned


推荐阅读