简体   繁体   English

如何同时按年份,月份和季节排序?

[英]How can I sort by year, month and season all at the same time?

So, I'm using this code to help sort a "Date" column in my table: 因此,我正在使用以下代码来帮助对表中的“日期”列进行排序:

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"monthYear-pre": function ( a ) {
    return new Date('01 '+a);
},

"monthYear-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},

"monthYear-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ?  -1 : 0));
}
} );

It works fine with dates such as "Jul 2012" but it won't cooperate with dates that have just the year (eg "2004) or have a season (eg Spring 2008). Also, if I've got "unknown" I'd like it to always appear last. 它可以很好地处理“ 2012年7月”之类的日期,但不能与只有年份(例如“ 2004”)或有季节(例如2008年春季)的日期配合使用。希望它总是出现在最后。

Any ideas? 有任何想法吗? I think making the seasons analogous to a month would be the easiest way to sort that (eg Spring=Mar, Summer=Jun, Autumn=Sep and Winter=Dec) but I'm not sure how to go about it. 我认为使季节类似于一个月将是最简单的排序方式(例如,春季= 3月,夏季= 6月,秋季= 9月和冬季= 12月),但我不确定如何进行。

Thank you! 谢谢!

PS I'm a novice - I kind of understand what the second two strings are doing, but the first "monthYear-pre" is a mystery. PS:我是新手-我有点理解后两个字符串在做什么,但是第一个“ monthYear-pre”是个谜。 If anyone would like to explain then I'd be thrilled. 如果有人想解释,那我会很高兴。

"seasonYear-pre": (function() {
    var seasons = /\s*(winter|spring|summer|fall|autumn),?\s*(\d{4})\s*/,
        matchedMonths = {winter: '02-01', spring: '05-01', 
                         summer: '08-01', fall: '11-01', autumn: '11-01'}
    return function(a) {
        var match = seasons.exec(a.toLowerCase());
        return new Date(match[2] + "-" + matchedMonths[match[1]]);
    };
})();

This places winter at the beginning of the year, but you can change the canonical dates in the list above as you please. 此处将冬季定为年初,但是您可以根据需要更改上面列表中的规范日期。 It matches strings like "Winter 2012", or "Autumn, 2007". 它匹配字符串“ Winter 2012”或“ Autumn,2007”。 (The comma is optional, and it's case-insensitive.) I don't know this table-sorter API. (逗号是可选的,并且不区分大小写。)我不知道此表排序器API。 I modeled this off the "monthYear-pre", but if it needs to be a plain sort method, it would be easy to change. 我以“ monthYear-pre”为模型,但是如果需要使用简单的排序方法,则很容易更改。

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

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