简体   繁体   English

如何使用 Javascript 按日期和时间排序

[英]How to sort by date and then by time using Javascript

I have written a script to help me convert a very long and tedious task of copying numbers from a paragraph and retyping them into a table.我编写了一个脚本来帮助我转换从段落中复制数字并将它们重新输入表格的非常冗长而乏味的任务。

However, I need to be able to sort these "paragraphs" by date, and then within each date, they have to be sorted by time (I know 3333Z is not a valid time, this is only for testing and to make sure it sorts correctly).但是,我需要能够按日期对这些“段落”进行排序,然后在每个日期内,它们必须按时间排序(我知道 3333Z 不是有效时间,这仅用于测试并确保它排序正确)。

This is how it needs to display as the final product.这就是它需要显示为最终产品的方式。 My code builds a CSV version of this table, that I paste into Excel to get the table.我的代码构建了该表的 CSV 版本,我将其粘贴到 Excel 中以获取该表。

March 4
--------------------------------------------------------------------------------------
|  Value 1    |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

March 12
--------------------------------------------------------------------------------------
|  Value 1    |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

March 29
--------------------------------------------------------------------------------------
|   Value 1   |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

I have a value called line1field2 that has the date and time in the format of DDHHHHZ.我有一个名为 line1field2 的值,它具有 DDHHHHZ 格式的日期和时间。 In the example above, DD would give 4, 12, and 29. Then is must sort by the time (HHHH) to create the table part.在上面的示例中,DD 将给出 4、12 和 29。然后必须按时间 (HHHH) 排序才能创建表部分。

I know this can be completed in other languages, but, due to system requirements, this must be in plain JavaScript, no libraries like jQuery, and it must work with FireFox 3.6.3.我知道这可以用其他语言完成,但是由于系统要求,这必须是普通的 JavaScript,没有像 jQuery 这样的库,它必须与 FireFox 3.6 一起使用。

This code below works, except it does not separate by date.下面的代码有效,但它没有按日期分隔。

Also, I would like to save this as CSV file (or a file that will keep the table format) as a final output, I know I could do with PHP, but I don't think I can do this with JavaScript. Also, I would like to save this as CSV file (or a file that will keep the table format) as a final output, I know I could do with PHP, but I don't think I can do this with JavaScript. If anyone knows of a way that this can be done, please let me know.如果有人知道可以做到这一点的方法,请告诉我。

If I was unclear on anything, please ask and I will try to explain it better.如果我有什么不清楚的地方,请询问,我会尽力解释得更好。

Thanks谢谢

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Converter</title>
    <style type="text/css">
    body {
        background: #C8C8C8;
        margin: 10px;
        font-size: 100%;
    }

    .floatstop {
        clear: both;
    }

    .hidden {
        display: none;
    }

    .unhidden {
        display: block;
    }

    #button {
        margin: 0px auto;
    }

    #instruction {
        margin: 5px;
        width: 500px;
    }

    #workspace {
        background: #FFFFFF;
        float: left;
        margin: 0px auto;
        height: 300px;
        width: 505px;    
        border-style: ridge;
        border-width: 5px;
        border-color: gray;
    }

#outer {
    background: #F0F0F0;
    width: 1035px;
    margin: 0px auto;
    padding: 10px;
    border-style: solid;
    border-width: 3px;
    border-color: black;
}

#preview {
    background:   #FFFFFF;
    float: right;
    margin: 0px auto;
    height: 300px;
    width: 505px;
    border-style: ridge;
    border-width: 5px;
    border-color: gray;
}

#viewCSV {
    width: 500px;    
}

#viewHTML {
    width: 500px;
}
</style>
</head>
<body>
<script type="text/javascript" language="JavaScript">

//Select text function in Preview textarea
function selectText(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

//Trim leading zeros    
function trimNumber(s) {
    while (s.substr(0, 1) == '0' && s.length > 1) { s = s.substr(1, 9999); }
    return s;
}

//Trim leading zeros, but leave two digits before decimal point
function trimNumber2(s) {
    while (s.substr(0, 2) == '00' && s.length > 1) { s = s.substr(1, 9999); }
    return s;
}

var row = [];
var results = [];

function conversionCode() {
    var pastedText = document.getElementById("pastedText").value; //get text from input
    var para = pastedText.split("\n\n");
    var i = 0;
    for (i = 0; i < para.length; i++) { //start conversion loop
        var report = para[i];

        //Arrays are zero-based.
        var splitLines     = report.split('//');
        var line1Arr       = splitLines[0];
        var line2Arr       = splitLines[1];
        var line3Arr       = splitLines[2];
        var line4Arr       = splitLines[3];
        var line5Arr       = splitLines[4];

        //Break out FIRST line.
        var lineAAA        = splitLines[0].split('/');
        var datasetName1   = lineAAA[0];
        var line1field1    = lineAAA[1];
        var line1field2    = lineAAA[2];
        var line1field3    = lineAAA[3];
        var line1field4    = lineAAA[4];
        var line1field5    = lineAAA[5];
        var line1field6    = lineAAA[6];
        var line1field7    = lineAAA[7];
        var line1field8    = lineAAA[8];
        var line1field9    = lineAAA[9];

        //Break out SECOND line.
        var lineBBBBB      = splitLines[1].split('/');
        var datasetName2   = lineBBBBB[0];
        var line2field1    = lineBBBBB[1];
        var line2field2    = lineBBBBB[2];
        var line2field3    = lineBBBBB[3];
        var line2field4    = lineBBBBB[4];
        var line2field5    = lineBBBBB[5];
        var line2field6    = lineBBBBB[6];
        var line2field7    = lineBBBBB[7];

        //Break out THIRD line.
        var lineCCC        = splitLines[2].split('/');
        var dataSetName3   = lineCCC[0];
        var line3field1    = lineCCC[1];
        var line3field2    = lineCCC[2];
        var line3field3    = lineCCC[3];
        var line3field4    = lineCCC[4];
        var line3field5    = lineCCC[5];

        //Break out FOURTH line.
        var lineDDDD1      = splitLines[3].split('/');
        var dataSetName4   = lineDDDD1[0];
        var line4field1    = lineDDDD1[1];
        var line4field2    = lineDDDD1[2];
        var line4field3    = lineDDDD1[3];
        var line4field4    = lineDDDD1[4];
        var line4field5    = lineDDDD1[5];
        var line4field6    = lineDDDD1[6];
        var line4field7    = lineDDDD1[7];

        //Break out FIFTH line.
        var lineDDDD2      = splitLines[4].split('/');
        var dataSetName5   = lineDDDD2[0];
        var line5field1    = lineDDDD2[1];
        var line5field2    = lineDDDD2[2];
        var line5field3    = lineDDDD2[3];
        var line5field4    = lineDDDD2[4];
        var line5field5    = lineDDDD2[5];
        var line5field6    = lineDDDD2[6];
        var line5field7    = lineDDDD2[7];

        //Change variables to correct formating
        //date - selecting and validating the date from line1field2
        var date = line1field2.slice(0, -5);
        var min = 1;
        var max = 31;
        var num = parseInt(date);
        if (min > num || max < num) {
            alert('Invalid date');
            exit();
        }

        //Time - Correcting format
        line1field2 = line1field2.slice(2);
        line1field3 = line1field3.slice(2);

        //line3field1 - remove letters from end of field, remove leading zeros
        line3field1 = line3field1.slice(0, -3);
        line3field1 = trimNumber(line3field1);

        //line3field3 - Split field on ':'
        line3field3 = line3field3.split(':');
        line3field3 = line3field3[1];

        //line4field1 - Split field on ':', and removing leading zeros
        line4field1 = line4field1.split(':');
        line4field1 = line4field1[1];
        line4field1 = trimNumber(line4field1);

        //line3field5 - Remove leading zeros, but keep at least two numbers before the
        //decimal point (Example: 01.123)
        line3field5 = line3field5.split(':');
        line3field5 = line3field5[1];
        line3field5 = trimNumber2(line3field5);

        //Create Array for each row in table.
        row[row.length] = line1field2;
        row[row.length] = line1field3;
        row[row.length] = line3field1;
        row[row.length] = line3field3;
        row[row.length] = line4field1;
        row[row.length] = line3field5;

        //Add each report's data to array'
        results.push(row);

        //Remove data from row for next loop 
        row = [];

    }

    //Sort results array for display
    results = results.sort();

    //Build HTML table

    //Build CSV text  
    resultsHeader = "Value 1,Value 2,Value 3,Value 4,Value 5,Value 6" + "\n";
    document.getElementById("plainOutput").innerHTML = resultsHeader;

    for (i = 0; i < results.length; i++) {
        document.getElementById("plainOutput").innerHTML += results[i] + "\n";
    }

};

</script>

<div id="outer">
    <h1 align="center">CONVERTER</h1>
    <div id="workspace">
    <h2 align="center">Workspace</h2>      
    <form action="" method="get" id="inputForm">
    <textarea id="pastedText" style="width:500px" rows="10"></textarea>
        <div id="button" class="floatstop">
        <p><input type="button" value="Convert" onclick="conversionCode ()"></p>    
        </div>
    </form>
    </div>
    <div id="preview">
    <h2 align="center">Preview</h2>
        <div id="viewCSV"> 
        <form action="" method="get" name="csvDisplay">  
        <textarea id="plainOutput" style="width: 500px" rows="10" readonly="readonly" onClick="selectText('plainOutput')"></textarea>
        <p><input type="button" value="Select Text" onClick="selectText('plainOutput')"/></p>
        </form>
        </div>
    </div>
    <div id="instruction" > 
    <p style="margin-left: 20px"><strong>Instructions:</strong></br>
    <ol>
        <li>Paste text into the Workspace.</li>
        <li>Click the "Convert" button.</li>
        <li>Cclick on the text or the Select button at the bottom to select 
            the text.</li>
        <li>You <strong>must</strong> copy the text by either Right-clicking 
            and choose Copy or by pressing Control+C.</li>
        <li>Paste the text into Excel as CSV.</li>
        <li>Format table as necessary.</li>
        <li>Select table and paste into product.</li>
    </ol>
    </div>
</div>
</body>
</html>

Convert the "times" to Date() objects (split the string, convert into numbers, feed the constructor).将“时间”转换为Date()对象(拆分字符串、转换为数字、输入构造函数)。

Then use the sort() method of your dates-array.然后使用日期数组的sort()方法。 Using a custom compareFunction, you can easily sort dates.使用自定义 compareFunction,您可以轻松地对日期进行排序。 Have a look at the number compare function in the linked docs: It will also work for Date objects because the will be implicitly converted into numbers.查看链接文档中的数字比较 function :它也适用于 Date 对象,因为它将被隐式转换为数字。

After that, you will be able to split the array up into subarrays for each date.之后,您将能够将数组拆分为每个日期的子数组。

export const sortByDate = (array, direction) => {
      if (!array.length) return []
      if (direction.toLowerCase() === "asc") {
        return array.sort(
          (a, b) => new Date(a).getTime() - new Date(b).getTime()
        )
      }
      if (direction.toLowerCase() === "desc") {
        return array.sort(
          (a, b) =>
            new Date(String(b)).getTime() -
            new Date(String(a)).getTime()
        )
      }
      return array
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM