/ckan/public/base/javascript/plugins/jquery.date-helpers.js

https://gitlab.com/iislod/ckan · JavaScript · 82 lines · 43 code · 9 blank · 30 comment · 6 complexity · 3c1cfd313bbac53f12d816cb3a2cab15 MD5 · raw file

  1. this.jQuery.date = {
  2. /* A map of date methods to text strings. */
  3. METHODS: {
  4. "yyyy": "getUTCFullYear",
  5. "MM": "getUTCMonth",
  6. "dd": "getUTCDate",
  7. "HH": "getUTCHours",
  8. "mm": "getUTCMinutes",
  9. "ss": "getUTCSeconds",
  10. "fff": "getUTCMilliseconds"
  11. },
  12. /* Formatting of an ISO8601 compatible date */
  13. ISO8601: "yyyy-MM-ddTHH:mm:ss.fffZ",
  14. /* Formatting of a CKAN compatible ISO string. See helpers.py */
  15. CKAN8601: "yyyy-MM-ddTHH:mm:ss",
  16. /* Returns a date string for the format provided.
  17. *
  18. * format - A format string in the form "yyyy-MM-dd"
  19. * date - A date object to output.
  20. *
  21. * Returns a formatted date string.
  22. */
  23. format: function (format, date) {
  24. var map = this.METHODS;
  25. date = date || new Date();
  26. function pad(str, exp) {
  27. str = "" + str;
  28. exp = exp.replace(/[a-z]/ig, '0');
  29. return str.length !== exp.length ? exp.slice(str.length) + str : str;
  30. }
  31. return format.replace(/([a-zA-Z])\1+/g, function (_, $1) {
  32. if (map[_]) {
  33. var value = date[map[_]]();
  34. if (_ === 'MM') {
  35. value += 1;
  36. }
  37. return pad(value, _);
  38. }
  39. return _;
  40. });
  41. },
  42. /* Generates a CKAN friendly ISO8601 timestamp.
  43. *
  44. * date - A date object to convert.
  45. *
  46. * Examples
  47. *
  48. * var timestamp = jQuery.date.toCKANString(new Date());
  49. *
  50. * Returns a timestamp string.
  51. */
  52. toCKANString: function (date) {
  53. return this.format(this.CKAN8601, date);
  54. },
  55. /* Generates a ISO8601 timestamp. Uses the native methods if available.
  56. *
  57. * date - A date object to convert.
  58. *
  59. * Examples
  60. *
  61. * var timestamp = jQuery.date.toISOString(new Date());
  62. *
  63. * Returns a timestamp string.
  64. */
  65. toISOString: function (date) {
  66. date = date || new Date();
  67. if (date.toISOString) {
  68. return date.toISOString();
  69. } else {
  70. return this.format(this.ISO8601, date);
  71. }
  72. }
  73. };