006-datetime-moment.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. function strip (d) {
  30. if ( typeof d === 'string' ) {
  31. // Strip HTML tags and newline characters if possible
  32. d = d.replace(/(<.*?>)|(\r?\n|\r)/g, '');
  33. // Strip out surrounding white space
  34. d = d.trim();
  35. }
  36. return d;
  37. }
  38. $.fn.dataTable.moment = function ( format, locale, reverseEmpties ) {
  39. var types = $.fn.dataTable.ext.type;
  40. // Add type detection
  41. types.detect.unshift( function ( d ) {
  42. d = strip(d);
  43. // Null and empty values are acceptable
  44. if ( d === '' || d === null ) {
  45. return 'moment-'+format;
  46. }
  47. return moment( d, format, locale, true ).isValid() ?
  48. 'moment-'+format :
  49. null;
  50. } );
  51. // Add sorting method - use an integer for the sorting
  52. types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
  53. d = strip(d);
  54. return !moment(d, format, locale, true).isValid() ?
  55. (reverseEmpties ? -Infinity : Infinity) :
  56. parseInt( moment( d, format, locale, true ).format( 'x' ), 10 );
  57. };
  58. };
  59. }));