如何对字符串日期数组进行排序

时间:2019-06-15 14:19:06

标签: swift string date nsmutablearray

我想按升序对数组进行排序。日期为字符串格式

Optional(["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"])

我正在尝试使用下面的代码,但是它不起作用。

aryEventTime = aryEventTime.sorted(by: { ($0 as AnyObject).date.compare($1.date) == ComparisonResult.orderedAscending })


aryEventTime = aryEventTime.sorted(by: {
            ($0 as AnyObject).date.compare(($1 as AnyObject).date) == .orderedDescending}) as? NSMutableArray

3 个答案:

答案 0 :(得分:2)

我不建议您按日期对字典进行排序。只需将这些字符串解析为适当的Date对象并对其进行排序就足够了:

let dateStrings = Optional(["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"])

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let sortedDates = dateStrings?.compactMap(formatter.date(from:)).sorted()

答案 1 :(得分:1)

我得到了答案:

$start = '12/01/2019'; $end ='31/01/2019';

$start = DateTime::createFromFormat('d/m/Y', $start);
$end = DateTime::createFromFormat('d/m/Y', $end);

$each = new DateInterval('P1D');
$period = new DatePeriod($start, $each, $end);

$dates = [];
foreach ($period as $date) {
    // Check if its between monday and wednesday 
    $weekday = intval($date->format('N'));
    if ($weekday >= 1 && $weekday <= 3)
       $dates[] = $date;
}

print_r($dates);

答案 2 :(得分:0)

您拥有的array中的String

let arr = ["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"]

除了将String转换为Date之外,您还可以使用sorted()对该数组进行排序,即

let sortedArr = arr.sorted()
print(sortedArr)

输出:

["2019-07-02", "2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12"]

注意:date strings在这种特殊情况下只能sorted,而不能进行转换。例如,如果strings的格式为yyyy-dd-MM,则简单的string sorting将不起作用。