util.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import moment from 'moment'
  2. function formatTime(time) {
  3. if (typeof time !== 'number' || time < 0) {
  4. return time
  5. }
  6. var hour = parseInt(time / 3600)
  7. time = time % 3600
  8. var minute = parseInt(time / 60)
  9. time = time % 60
  10. var second = time
  11. return ([hour, minute, second]).map(function(n) {
  12. n = n.toString()
  13. return n[1] ? n : '0' + n
  14. }).join(':')
  15. }
  16. function formatLocation(longitude, latitude) {
  17. if (typeof longitude === 'string' && typeof latitude === 'string') {
  18. longitude = parseFloat(longitude)
  19. latitude = parseFloat(latitude)
  20. }
  21. longitude = longitude.toFixed(2)
  22. latitude = latitude.toFixed(2)
  23. return {
  24. longitude: longitude.toString().split('.'),
  25. latitude: latitude.toString().split('.')
  26. }
  27. }
  28. var dateUtils = {
  29. UNITS: {
  30. '年': 31557600000,
  31. '月': 2629800000,
  32. '天': 86400000,
  33. '小时': 3600000,
  34. '分钟': 60000,
  35. '秒': 1000
  36. },
  37. humanize: function(milliseconds) {
  38. var humanize = '';
  39. for (var key in this.UNITS) {
  40. if (milliseconds >= this.UNITS[key]) {
  41. humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
  42. break;
  43. }
  44. }
  45. return humanize || '刚刚';
  46. },
  47. format: function(dateStr) {
  48. var date = this.parse(dateStr)
  49. var diff = Date.now() - date.getTime();
  50. if (diff < this.UNITS['天']) {
  51. return this.humanize(diff);
  52. }
  53. var _format = function(number) {
  54. return (number < 10 ? ('0' + number) : number);
  55. };
  56. return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
  57. _format(date.getHours()) + ':' + _format(date.getMinutes());
  58. },
  59. parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串,转化为一个Date对象
  60. var a = str.split(/[^0-9]/);
  61. return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
  62. }
  63. };
  64. /**
  65. *对Date的扩展,将 Date 转化为指定格式的String
  66. *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
  67. *年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  68. *例子:
  69. *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  70. *(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  71. */
  72. Date.prototype.Format = function(fmt) { //author: meizz
  73. var o = {
  74. "M+": this.getMonth() + 1, //月份
  75. "d+": this.getDate(), //日
  76. "H+": this.getHours(), //小时
  77. "m+": this.getMinutes(), //分
  78. "s+": this.getSeconds(), //秒
  79. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  80. "S": this.getMilliseconds() //毫秒
  81. };
  82. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  83. for (var k in o)
  84. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
  85. "00" + o[
  86. k]).substr(("" + o[k]).length)));
  87. return fmt;
  88. }
  89. Array.prototype.indexOf = function(val) {
  90. for (var i = 0; i < this.length; i++) {
  91. if (this[i] == val) {
  92. return i;
  93. }
  94. }
  95. return -1;
  96. }
  97. Array.prototype.remove = function(val) {
  98. var index = this.indexOf(val);
  99. if (index > -1) {
  100. this.splice(index, 1);
  101. }
  102. }
  103. String.prototype.Trim = function() {
  104. return this.replace(/(^\s*)|(\s*$)/g, "");
  105. }
  106. String.prototype.LTrim = function() {
  107. return this.replace(/(^\s*)/g, "");
  108. }
  109. String.prototype.RTrim = function() {
  110. return this.replace(/(\s*$)/g, "");
  111. }
  112. function formatNumber(n) {
  113. n = n.toString()
  114. return n[1] ? n : '0' + n
  115. }
  116. function objectToUrlParams(obj) {
  117. var str = "";
  118. for (var key in obj) {
  119. str += "&" + key + "=" + obj[key];
  120. }
  121. return str.substr(1);
  122. }
  123. function getDate(type) {
  124. const date = new Date();
  125. let year = date.getFullYear();
  126. let month = date.getMonth() + 1;
  127. let day = date.getDate();
  128. if (type === 'start') {
  129. year = year - 60;
  130. } else if (type === 'end') {
  131. year = year + 2;
  132. }
  133. month = month > 9 ? month : '0' + month;
  134. day = day > 9 ? day : '0' + day;
  135. return `${year}-${month}-${day}`;
  136. }
  137. function formatDate(date, type = 2) {
  138. if (type === 1) {
  139. return moment(date).format('HH:mm')
  140. } else if (type === 2) {
  141. return moment(date).format('YYYY-MM-DD HH:mm')
  142. } else if (type === 3) {
  143. return moment(date).format('YYYY.MM.DD')
  144. } else if (type === 4) {
  145. return moment(date).format('HH:mm:ss')
  146. } else if (type === 5) {
  147. return moment(date).format('YYYY-MM-DD HH:mm:ss')
  148. } else if (type === 6) {
  149. const result = moment(date).format('M月DD日 Ah:mm')
  150. return result.includes('PM') ? result.replace('PM', '下午') : result.replace('AM', '上午')
  151. } else if (type === 7) {
  152. return moment(date).format('MM-DD HH:mm')
  153. } else if (type === 8) {
  154. return moment(date).format('YYYY年MM月DD日')
  155. } else if(type === 9) {
  156. return moment(date).format('YYYY-MM-DD HH:mm:ss ddd')
  157. } else {
  158. return moment(date).locale().format('YYYY-MM-DD HH:mm:ss')
  159. }
  160. }
  161. /*获取当前时间*/
  162. function getNowTime() {
  163. return Math.round(new Date().getTime() / 1000)
  164. }
  165. // 判断是否在签到时间内
  166. function signBetweenTime(beginTime = undefined, endTime = undefined) {
  167. return new moment().isBetween(beginTime, endTime, null, '[]')
  168. }
  169. // 比较时间在此之前
  170. function isBefore(time = undefined, cTime = undefined) {
  171. if(!cTime) {
  172. return new moment().isBefore(time)
  173. }
  174. return new moment(cTime).isBefore(time)
  175. }
  176. function isAfter(time = undefined, cTime = undefined) {
  177. if(!cTime) {
  178. return new moment().isAfter(time)
  179. }
  180. return new moment(cTime).isAfter(time)
  181. }
  182. function openDocument(urlPath) {
  183. // #ifdef APP
  184. uni.$u.toast('正在加载文件...')
  185. uni.downloadFile({
  186. url: urlPath,
  187. success: function(res) {
  188. uni.$u.toast('文件加载成功')
  189. const filePath = res.tempFilePath
  190. uni.openDocument({
  191. filePath,
  192. showMenu: true,
  193. success: function(res) {
  194. console.log('打开文档成功')
  195. }
  196. })
  197. }
  198. })
  199. // #endif
  200. // #ifndef APP
  201. uni.openDocument({
  202. filePath: urlPath
  203. })
  204. // #endif
  205. }
  206. // 金额小数点格式化, len是需要精确的小数点位数
  207. function toFixedFun(data, len) {
  208. const number = Number(data);
  209. if (isNaN(number) || number >= Math.pow(10, 21)) {
  210. return number.toString();
  211. }
  212. if (typeof(len) === 'undefined' || len === 0) {
  213. return (Math.round(number)).toString();
  214. }
  215. let result = number.toString();
  216. const numberArr = result.split('.');
  217. if (numberArr.length < 2) {
  218. // 整数的情况
  219. return padNum(result);
  220. }
  221. const intNum = numberArr[0]; // 整数部分
  222. const deciNum = numberArr[1]; // 小数部分
  223. const lastNum = deciNum.substr(len, 1); // 最后一个数字
  224. if (deciNum.length === len) {
  225. // 需要截取的长度等于当前长度
  226. return result;
  227. }
  228. if (deciNum.length < len) {
  229. // 需要截取的长度大于当前长度 1.3.toFixed(2)
  230. return padNum(result);
  231. }
  232. // 需要截取的长度小于当前长度,需要判断最后一位数字
  233. result = `${intNum}.${deciNum.substr(0, len)}`;
  234. if (parseInt(lastNum, 10) >= 5) {
  235. // 最后一位数字大于5,要进位
  236. const times = Math.pow(10, len); // 需要放大的倍数
  237. let changedInt = Number(result.replace('.', '')); // 截取后转为整数
  238. changedInt++; // 整数进位
  239. changedInt /= times; // 整数转为小数,注:有可能还是整数
  240. result = padNum(`${changedInt }`);
  241. }
  242. return result;
  243. // 对数字末尾加0
  244. function padNum(num) {
  245. const dotPos = num.indexOf('.');
  246. if (dotPos === -1) {
  247. // 整数的情况
  248. num += '.';
  249. for (let i = 0; i < len; i++) {
  250. num += '0';
  251. }
  252. return num;
  253. } else {
  254. // 小数的情况
  255. const need = len - (num.length - dotPos - 1);
  256. for (let j = 0; j < need; j++) {
  257. num += '0';
  258. }
  259. return num;
  260. }
  261. }
  262. }
  263. // 格式化手机号码*
  264. function formatPhone(value) {
  265. if(!value) return ''
  266. if(value.toString().trim().length != 11) {
  267. return value
  268. }
  269. const phone = value.toString().trim().split('')
  270. phone.splice(3,4,'****')
  271. return phone.join('')
  272. }
  273. // 格式化身份证号*
  274. function formatIdCard(value) {
  275. if(!value) return ''
  276. const valueStr = value.toString().trim()
  277. if(valueStr.length != 18) {
  278. return value
  279. }
  280. const idcard = value.toString().trim().split('')
  281. idcard.splice(6,8,'********')
  282. return idcard.join('')
  283. }
  284. module.exports = {
  285. formatTime: formatTime,
  286. formatLocation: formatLocation,
  287. dateUtils: dateUtils,
  288. objectToUrlParams: objectToUrlParams,
  289. getDate: getDate,
  290. getNowTime: getNowTime,
  291. formatDate: formatDate,
  292. openDocument: openDocument,
  293. signBetweenTime: signBetweenTime,
  294. isBefore: isBefore,
  295. isAfter: isAfter,
  296. toFixedFun: toFixedFun,
  297. formatPhone: formatPhone,
  298. formatIdCard: formatIdCard
  299. }