utils.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import * as C from './constant';
  2. var padStart = function padStart(string, length, pad) {
  3. var s = String(string);
  4. if (!s || s.length >= length) return string;
  5. return "" + Array(length + 1 - s.length).join(pad) + string;
  6. };
  7. var padZoneStr = function padZoneStr(instance) {
  8. var negMinutes = -instance.utcOffset();
  9. var minutes = Math.abs(negMinutes);
  10. var hourOffset = Math.floor(minutes / 60);
  11. var minuteOffset = minutes % 60;
  12. return "" + (negMinutes <= 0 ? '+' : '-') + padStart(hourOffset, 2, '0') + ":" + padStart(minuteOffset, 2, '0');
  13. };
  14. var monthDiff = function monthDiff(a, b) {
  15. // function from moment.js in order to keep the same result
  16. if (a.date() < b.date()) return -monthDiff(b, a);
  17. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month());
  18. var anchor = a.clone().add(wholeMonthDiff, C.M);
  19. var c = b - anchor < 0;
  20. var anchor2 = a.clone().add(wholeMonthDiff + (c ? -1 : 1), C.M);
  21. return +(-(wholeMonthDiff + (b - anchor) / (c ? anchor - anchor2 : anchor2 - anchor)) || 0);
  22. };
  23. var absFloor = function absFloor(n) {
  24. return n < 0 ? Math.ceil(n) || 0 : Math.floor(n);
  25. };
  26. var prettyUnit = function prettyUnit(u) {
  27. var special = {
  28. M: C.M,
  29. y: C.Y,
  30. w: C.W,
  31. d: C.D,
  32. D: C.DATE,
  33. h: C.H,
  34. m: C.MIN,
  35. s: C.S,
  36. ms: C.MS,
  37. Q: C.Q
  38. };
  39. return special[u] || String(u || '').toLowerCase().replace(/s$/, '');
  40. };
  41. var isUndefined = function isUndefined(s) {
  42. return s === undefined;
  43. };
  44. export default {
  45. s: padStart,
  46. z: padZoneStr,
  47. m: monthDiff,
  48. a: absFloor,
  49. p: prettyUnit,
  50. u: isUndefined
  51. };