You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.4 KiB

  1. /**
  2. * This plug-in for DataTables represents the ultimate option in extensibility
  3. * for sorting date / time strings correctly. It uses
  4. * [Moment.js](http://momentjs.com) to create automatic type detection and
  5. * sorting plug-ins for DataTables based on a given format. This way, DataTables
  6. * will automatically detect your temporal information and sort it correctly.
  7. *
  8. * For usage instructions, please see the DataTables blog
  9. * post that [introduces it](//datatables.net/blog/2014-12-18).
  10. *
  11. * @name Ultimate Date / Time sorting
  12. * @summary Sort date and time in any format using Moment.js
  13. * @author [Allan Jardine](//datatables.net)
  14. * @depends DataTables 1.10+, Moment.js 1.7+
  15. *
  16. * @example
  17. * $.fn.dataTable.moment( 'HH:mm MMM D, YY' );
  18. * $.fn.dataTable.moment( 'dddd, MMMM Do, YYYY' );
  19. *
  20. * $('#example').DataTable();
  21. */
  22. (function (factory) {
  23. if (typeof define === "function" && define.amd) {
  24. define(["jquery", "moment", "datatables.net"], factory);
  25. } else {
  26. factory(jQuery, moment);
  27. }
  28. }(function ($, moment) {
  29. $.fn.dataTable.moment = function ( format, locale ) {
  30. var types = $.fn.dataTable.ext.type;
  31. // Add type detection
  32. types.detect.unshift( function ( d ) {
  33. if ( d ) {
  34. // Strip HTML tags and newline characters if possible
  35. if ( d.replace ) {
  36. d = d.replace(/(<.*?>)|(\r?\n|\r)/g, '');
  37. }
  38. // Strip out surrounding white space
  39. d = $.trim( d );
  40. }
  41. // Null and empty values are acceptable
  42. if ( d === '' || d === null ) {
  43. return 'moment-'+format;
  44. }
  45. return moment( d, format, locale, true ).isValid() ?
  46. 'moment-'+format :
  47. null;
  48. } );
  49. // Add sorting method - use an integer for the sorting
  50. types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
  51. if ( d ) {
  52. // Strip HTML tags and newline characters if possible
  53. if ( d.replace ) {
  54. d = d.replace(/(<.*?>)|(\r?\n|\r)/g, '');
  55. }
  56. // Strip out surrounding white space
  57. d = $.trim( d );
  58. }
  59. return d === '' || d === null ?
  60. -Infinity :
  61. parseInt( moment( d, format, locale, true ).format( 'x' ), 10 );
  62. };
  63. };
  64. }));