你会如何处理不同格式的日期?

时间:2017-07-31 13:54:32

标签: javascript jquery wikipedia wikipedia-api

我有不同类型的日期格式,如:

  • 663年8月27日至28日

  • 1945年8月22日19月19日

  • 1945年5月4日 - 1945年8月22日

  • 1945年5月4日

  • 1232年2月7日

  • 1020年3月4日

  • 1/3/1 (year 1)

  • 09/08/0 (year 0)

请注意,它们都是不同的格式,不同的顺序,有些有2个月,有些只有一个,我尝试使用moment js没有结果,我还尝试使用date js但没有运气。

我试图做一些拆分:

dates.push({
    Time : []
});

function doSelect(text) {
  return $wikiDOM.find(".infobox th").filter(function() {
    return $(this).text() === text;
  });
}
dateText = doSelect("Date").siblings('td').text().split(/\s+/g);
 for(var i = 0; i < dateText.length; i++) {
  d += dateText[i] + ' ';
}
dates[0].Time.push(d);

但结果是:

"Time": [
            "27 - 28 August 663 CE ",

最终我需要自动生成的是:

<ul class="Days">
  <li>27</li>
  <li>28</li>
</ul>

<ul class="Months">
  <li>August</li>
</ul>

<ul class="Year">
  <li>663</li>
</ul>

还想到一种处理CEADBC

的方法

为了实现这个我想要使用的理想方式是一个多维数组:

time.push({
    Day : [], 
    Month : [],
    Year : [],
    Prefix : []
});

可能要检查max 2 numbers for days,请根据January, February, March..等字符串列表检查月份,然后检查年份3 numbers to max 4 numbers,然后处理prefix with some conditionals。但是,year 2 or 1怎么样?或者如果日期是02/9/1975怎么样?或者通过分隔dash,它们将成为一种新格式。我认为那里的逻辑很有点但是你会如何将这些日期分成多维数组,因为它们都是不同的格式?

1 个答案:

答案 0 :(得分:0)

  

我将在构建新解析器时越来越多地更新此答案。随意贡献。

对于这些格式,我会这样做:

27 - 28 August 663 CE
22 August 1945 19 May
May 4 1945 – August 22 1945
5-10 February 1720

JS

months = new Set(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
for(var i = 0; i < dateText.length; i++) {
  d += dateText[i] + ' ';
}
var words = d.replace("–", " ").replace("-", " ").replace(",", " ").replace("/", " ").split(' ');
words = $.grep(words, function(n, i){
    return (n !== "" && n != null);
});
var array = words;
var newArray = array.filter(function(v){return v!==''});
for (const word of newArray) {
 if (months.has(word)) {
   spacetime[0].Time.months.push(word);
 } else if (+word < 32) {
   spacetime[0].Time.days.push(+word);
 } else if (+word < 2200) {
   spacetime[0].Time.years.push(+word);
 } else if (/\w+/.test(word)) {
   spacetime[0].Time.suffixes.push(word);
}

jSon例子:

        "Time": {
            "days": [
                22
            ],
            "months": [
                "August"
            ],
            "years": [
                1945
            ],
            "suffixes": [
                "10:25",
                "(UTC+1)"
            ]
相关问题