util2.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /**函数防抖
  2. * @param { function } func
  3. * @param { number } wait 延迟执行毫秒数
  4. * @param { boolean } immediate true 表立即执行,false 表非立即执行
  5. */
  6. function debounce(func, wait = 100, immediate = false) {
  7. let timeout
  8. return function() {
  9. let context = this
  10. let args = arguments
  11. if (timeout) clearTimeout(timeout)
  12. if (immediate) {
  13. let callNow = !timeout
  14. timeout = setTimeout(() => {
  15. timeout = null
  16. }, wait)
  17. if (callNow) func.apply(context, args)
  18. } else {
  19. timeout = setTimeout(() => {
  20. func.apply(context, args)
  21. }, wait)
  22. }
  23. }
  24. }
  25. /**函数节流
  26. * @param { function } func 函数
  27. * @param { number } wait 延迟执行毫秒数
  28. * @param { number } type 1 表时间戳版,2 表定时器版
  29. */
  30. function throttle(func, wait = 100, type = 2) {
  31. let previous, timeout
  32. if (type === 1) {
  33. previous = 0
  34. } else if (type === 2) {
  35. timeout = null
  36. }
  37. return function() {
  38. let context = this
  39. let args = arguments
  40. if (type === 1) {
  41. let now = Date.now()
  42. if (now - previous > wait) {
  43. func.apply(context, args)
  44. previous = now
  45. }
  46. } else if (type === 2) {
  47. if (!timeout) {
  48. timeout = setTimeout(() => {
  49. timeout = null
  50. func.apply(context, args)
  51. }, wait)
  52. }
  53. }
  54. }
  55. }
  56. function forMatNum(num) {
  57. return num < 10 ? '0' + num : num + '';
  58. }
  59. function initDays(year, month) {
  60. let totalDays = new Date(year, month, 0).getDate();
  61. let dates = [];
  62. for (let d = 1; d <= totalDays; d++) {
  63. dates.push(forMatNum(d));
  64. };
  65. return dates;
  66. }
  67. function initPicker(start, end, mode = "date", step) {
  68. let initstartDate = new Date(start);
  69. let endDate = new Date(end);
  70. let startYear = initstartDate.getFullYear();
  71. let startMonth = initstartDate.getMonth();
  72. let endYear = endDate.getFullYear();
  73. let years = [],
  74. months = [],
  75. days = [],
  76. hours = [],
  77. minutes = [],
  78. seconds = [];
  79. let totalDays = new Date(startYear, startMonth, 0).getDate();
  80. for (let s = startYear; s <= endYear; s++) {
  81. years.push(s + '');
  82. };
  83. for (let m = 1; m <= 12; m++) {
  84. months.push(forMatNum(m));
  85. };
  86. for (let d = 1; d <= totalDays; d++) {
  87. days.push(forMatNum(d));
  88. }
  89. for (let h = 0; h < 24; h++) {
  90. hours.push(forMatNum(h));
  91. }
  92. for (let m = 0; m < 60; m += step * 1) {
  93. minutes.push(forMatNum(m));
  94. }
  95. for (let s = 0; s < 60; s++) {
  96. seconds.push(forMatNum(s));
  97. }
  98. switch (mode) {
  99. case "date":
  100. return {
  101. years,
  102. months,
  103. days
  104. }
  105. break;
  106. case "yearMonth":
  107. return {
  108. years,
  109. months
  110. }
  111. break;
  112. case "dateTime":
  113. return {
  114. years,
  115. months,
  116. days,
  117. hours,
  118. minutes,
  119. seconds
  120. }
  121. break;
  122. case "time":
  123. return {
  124. hours,
  125. minutes,
  126. seconds
  127. }
  128. break;
  129. }
  130. }
  131. function getDate(type) {
  132. const date = new Date();
  133. let year = date.getFullYear();
  134. if (type === 'start') {
  135. year = year - 60;
  136. } else if (type === 'end') {
  137. year = year + 2;
  138. }
  139. return `${year}`;
  140. }
  141. function formatTime(time) {
  142. if (typeof time !== 'number' || time < 0) {
  143. return time
  144. }
  145. var hour = parseInt(time / 3600)
  146. time = time % 3600
  147. var minute = parseInt(time / 60)
  148. time = time % 60
  149. var second = time
  150. return ([hour, minute, second]).map(function(n) {
  151. n = n.toString()
  152. return n[1] ? n : '0' + n
  153. }).join(':')
  154. }
  155. function formatLocation(longitude, latitude) {
  156. if (typeof longitude === 'string' && typeof latitude === 'string') {
  157. longitude = parseFloat(longitude)
  158. latitude = parseFloat(latitude)
  159. }
  160. longitude = longitude.toFixed(2)
  161. latitude = latitude.toFixed(2)
  162. return {
  163. longitude: longitude.toString().split('.'),
  164. latitude: latitude.toString().split('.')
  165. }
  166. }
  167. var dateUtils = {
  168. UNITS: {
  169. '年': 31557600000,
  170. '月': 2629800000,
  171. '天': 86400000,
  172. '小时': 3600000,
  173. '分钟': 60000,
  174. '秒': 1000
  175. },
  176. humanize: function(milliseconds) {
  177. var humanize = '';
  178. for (var key in this.UNITS) {
  179. if (milliseconds >= this.UNITS[key]) {
  180. humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
  181. break;
  182. }
  183. }
  184. return humanize || '刚刚';
  185. },
  186. format: function(dateStr) {
  187. var date = this.parse(dateStr)
  188. var diff = Date.now() - date.getTime();
  189. if (diff < this.UNITS['天']) {
  190. return this.humanize(diff);
  191. }
  192. var _format = function(number) {
  193. return (number < 10 ? ('0' + number) : number);
  194. };
  195. return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
  196. _format(date.getHours()) + ':' + _format(date.getMinutes());
  197. },
  198. parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串,转化为一个Date对象
  199. var a = str.split(/[^0-9]/);
  200. return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
  201. }
  202. };
  203. function formatDate(value, fmt) {
  204. let regPos = /^\d+(\.\d+)?$/;
  205. if (regPos.test(value)) {
  206. //如果是数字
  207. let getDate = new Date(value);
  208. let o = {
  209. 'M+': getDate.getMonth() + 1,
  210. 'd+': getDate.getDate(),
  211. 'h+': getDate.getHours(),
  212. 'm+': getDate.getMinutes(),
  213. 's+': getDate.getSeconds(),
  214. 'q+': Math.floor((getDate.getMonth() + 3) / 3),
  215. 'S': getDate.getMilliseconds()
  216. };
  217. if (/(y+)/.test(fmt)) {
  218. fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
  219. }
  220. for (let k in o) {
  221. if (new RegExp('(' + k + ')').test(fmt)) {
  222. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k])
  223. .length)))
  224. }
  225. }
  226. return fmt;
  227. } else {
  228. //TODO
  229. value = value.trim();
  230. return value.substr(0, fmt.length);
  231. }
  232. }
  233. //获取当前的平台(终端类型 1 android 2 ios 3 h5 4 微信小程序 5 web)
  234. function getPlatform() {
  235. //默认web
  236. let platform = 5;
  237. //#ifdef APP-PLUS || APP-NVUE
  238. const system = uni.getSystemInfoSync();
  239. if (system.platform === "ios") {
  240. platform = 1;
  241. } else {
  242. platform = 2;
  243. }
  244. //#endif
  245. //#ifdef H5
  246. platform = 3;
  247. //#endif
  248. //#ifdef MP-WEIXIN
  249. platform = 4;
  250. //#endif
  251. return platform;
  252. };
  253. //判断浏览器是否是微信浏览器
  254. function checkIsWechatBrowser() {
  255. let platform = getPlatform();
  256. if (platform === 3) {
  257. return (
  258. navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
  259. "micromessenger"
  260. );
  261. } else {
  262. return false;
  263. }
  264. };
  265. module.exports = {
  266. formatTime: formatTime,
  267. formatLocation: formatLocation,
  268. dateUtils: dateUtils,
  269. getDate: getDate,
  270. initPicker: initPicker,
  271. forMatNum: forMatNum,
  272. initDays: initDays,
  273. getPlatform: getPlatform,
  274. checkIsWechatBrowser: checkIsWechatBrowser,
  275. debounce: debounce,
  276. throttle: throttle,
  277. formatDate: formatDate
  278. }