How would you handle different formats of dates?

前端 未结 1 1649
遇见更好的自我
遇见更好的自我 2020-12-12 06:40

I have different types of dates formatting like:

  • 27 - 28 August 663 CE

  • 22 August 1945 19 May

  • May 4 1945 – August 22 1945

相关标签:
1条回答
  • 2020-12-12 07:17

    I will be updating this answer more and more while I will build new parsers. Feel free to contribute.

    So for these formats, I'll do:

    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 example:

            "Time": {
                "days": [
                    22
                ],
                "months": [
                    "August"
                ],
                "years": [
                    1945
                ],
                "suffixes": [
                    "10:25",
                    "(UTC+1)"
                ]
    
    0 讨论(0)
提交回复
热议问题