1

我有一个日期列表,格式如下:YYYY-MM-DD

我希望能够按年(2013 年、2012 年、2011 年)按降序对它们进行排序,然后按月(1 月、2 月、3 月……)升序对它们进行排序。所以我要找的是:

2013-01-01
2013-02-01
2013-03-01
2013-04-01
2013-05-01

2012-01-01
2012-02-01
2012-03-01
...
2012-12-01

2011-01-01
2011-02-01
2011-03-01
...
2011-12-01

请注意,本年度的列表在 12 月之前是不完整的,所以这就是为什么它只到 2013-05-01。前几年将从 1 月到 12 月完成。

我做了一个类似于这样的冒泡排序:

For i = 0 to Ubound(dateArray)
    For j = i + 1 to Ubound(dateArray) 
        if dateArray(i) > dateArray(j) then
            tempDate = dateArray(i)         
            dateArray(i) = dateArray(j)
            dateArray(j) = tempDate
        end if
    Next  
Next

但这给了我一个看起来像这样的列表:

2011-01-01
2011-02-01
2011-03-01
...
2011-12-01

2012-01-01
2012-02-01
2012-03-01
...
2012-12-01

2013-01-01
2013-02-01
2013-03-01
2013-04-01
2013-05-01

关闭,但不完全。

4

2 回答 2

2

当两个日期的年份相同时,您需要升序排序,而当年份不同时,您需要降序:

Sub SwapValues(ByRef a, ByRef b)
    buf = a : a = b : b = buf
End Sub

...

If Year(dateArray(i)) = Year(dateArray(j)) Then
  If dateArray(i) > dateArray(j) Then
    SwapValues dateArray(i), dateArray(j)
  End If
Else
  If dateArray(i) < dateArray(j) Then
    SwapValues dateArray(i), dateArray(j)
  End If
End If

我添加了一个交换值的过程以稍微简化代码。

于 2013-07-26T17:44:05.857 回答
1

我以前见过这个......我想这就是我解决它的方法。

For i = 0 to Ubound(dateArray)
    For j = i + 1 to Ubound(dateArray) 
        if (year(dateArray(i)) < year(dateArray(j))) or (year(dateArray(i)) = year(dateArray(j)) and month(dateArray(i)) > month(dateArray(j)))then
            tempDate = dateArray(i)         
            dateArray(i) = dateArray(j)
            dateArray(j) = tempDate
        end if
    Next  
Next
于 2013-07-26T16:45:40.790 回答