util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  2. const toHideToast = debounce(options => {
  3. wx.showToast(options)
  4. }, 400)
  5. function platform() {
  6. let systemInfo = {}
  7. let u = ''
  8. wx.getSystemInfo({
  9. success(res) {
  10. systemInfo = res
  11. u = systemInfo.system || ''
  12. }
  13. })
  14. return {
  15. ...systemInfo,
  16. ios: u.indexOf('iOS') > -1, // ios终端
  17. android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 // android终端或uc浏览器
  18. }
  19. }
  20. function addMultiMonth(dtstr, n) {
  21. let yy = parseInt(dtstr[0])
  22. let mm = parseInt(dtstr[1])
  23. let dd = parseInt(dtstr[2])
  24. const dt = new Date(yy, mm, dd)
  25. const num = dt.getMonth() + parseInt(n)
  26. if (num / 12 > 1) {
  27. yy += Math.floor(num / 12)
  28. mm = num % 12
  29. } else {
  30. mm += parseInt(n)
  31. }
  32. return [yy, mm, dd]
  33. }
  34. function range(n, m, polyfill = false, unit = '') {
  35. const arr = []
  36. for (let i = n; i <= m; i++) {
  37. const value = (polyfill && i < 10 ? '0' + i : i) + unit
  38. arr.push({
  39. text: value,
  40. value: i
  41. })
  42. }
  43. return arr
  44. }
  45. function glDate() {
  46. const date = new Date()
  47. const YEAR = date.getFullYear()
  48. const MONTH = date.getMonth() + 1
  49. const DAY = date.getDate()
  50. const min = [YEAR, MONTH, DAY]
  51. // 产品要求:可选时间范围未来3个月内
  52. const max = addMultiMonth(min, 3)
  53. const data = range(min[0], max[0], false, '')
  54. data.forEach(year => {
  55. const minMonth = year.value === min[0] ? min[1] : 1
  56. const maxMonth = year.value === max[0] ? max[1] : 12
  57. year.children = range(minMonth, maxMonth, true, '')
  58. year.children.forEach(month => {
  59. let day = 30
  60. if ([1, 3, 5, 7, 8, 10, 12].indexOf(month.value) > -1) {
  61. day = 31
  62. } else {
  63. if (month.value === 2) {
  64. day = !(year.value % 400) || (!(year.value % 4) && year.value % 100) ? 29 : 28
  65. }
  66. }
  67. const minDay = year.value === min[0] && month.value === min[1] ? min[2] : 1
  68. const maxDay = year.value === max[0] && month.value === max[1] ? max[2] : day
  69. month.children = range(minDay, maxDay, true, '')
  70. })
  71. })
  72. return data
  73. }
  74. function formatGlDate() {
  75. const MINUTES = ['00', '10', '20', '30', '40', '50']
  76. const arr = glDate()
  77. const result = []
  78. for (let i = 0; i < arr.length; i++) {
  79. const YYYY = arr[i].text
  80. for (let j = 0; j < arr[i].children.length; j++) {
  81. const MM = arr[i].children[j].text
  82. for (let k = 0; k < arr[i].children[j].children.length; k++) {
  83. const DD = arr[i].children[j].children[k].text
  84. result.push(`${YYYY}-${MM}-${DD}`)
  85. }
  86. }
  87. }
  88. const one = result.map((item, index) => {
  89. const cur = new Date(platform().ios ? item.replace(/-/g, '/') : item).getDay()
  90. const value = item.replace('-', '年').replace('-', '月') + '日' + ' ' + WEEK[cur]
  91. return {
  92. value: (index + 11).toString(),
  93. text: value.replace(/(.*年)(.*)/, '$2'),
  94. _text: value.replace(/日.*/, '').replace(/年|月/g, '-')
  95. }
  96. })
  97. const two = range(0, 23, true, '').map((item, index) => {
  98. return {
  99. value: '11' + (index < 10 ? '0' + index : index),
  100. text: item.text + '时',
  101. _text: item.text
  102. }
  103. })
  104. const three = MINUTES.map((item, index) => {
  105. return {
  106. value: '1100' + (index < 10 ? '0' + index : index),
  107. text: item + '分',
  108. _text: item
  109. }
  110. })
  111. return {
  112. one,
  113. two,
  114. three
  115. }
  116. }
  117. const formatTime = date => {
  118. const year = date.getFullYear()
  119. const month = date.getMonth() + 1
  120. const day = date.getDate()
  121. const hour = date.getHours()
  122. const minute = date.getMinutes()
  123. const second = date.getSeconds()
  124. return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(
  125. formatNumber).join(':')}`
  126. }
  127. const formatArr = (arr) => {
  128. while (arr.some(item => Array.isArray(item))) {
  129. arr = [].concat(...arr)
  130. }
  131. return arr
  132. }
  133. function formatNumber(n) {
  134. n = n.toString()
  135. return n[1] ? n : `0${n}`
  136. }
  137. function cutDownTime(ts = 0, type) {
  138. if (ts < 0) {
  139. return ['0', '00', '00', '00']
  140. }
  141. ts = parseInt(ts)
  142. var D = Math.floor(ts / 24 / 60 / 60)
  143. // 小时位
  144. var h = Math.floor((ts - D * 24 * 60 * 60) / 3600)
  145. // 分钟位
  146. var m = Math.floor((ts - D * 24 * 3600 - h * 3600) / 60)
  147. // 秒位
  148. var s = ts - D * 24 * 3600 - h * 3600 - m * 60
  149. if (['hh:mm:ss'].includes(type)) {
  150. return `${formatNumber(D * 24 + h)}:${formatNumber(m)}:${formatNumber(s)}`
  151. }
  152. if (type === 'hh:mm zh') {
  153. return (D * 24 + h) + '小时' + m + '分'
  154. }
  155. return [D, formatNumber(h), formatNumber(m), formatNumber(s)]
  156. }
  157. function formatLocation(longitude, latitude) {
  158. if (typeof longitude === 'string' && typeof latitude === 'string') {
  159. longitude = parseFloat(longitude)
  160. latitude = parseFloat(latitude)
  161. }
  162. longitude = longitude.toFixed(2)
  163. latitude = latitude.toFixed(2)
  164. return {
  165. longitude: longitude.toString().split('.'),
  166. latitude: latitude.toString().split('.')
  167. }
  168. }
  169. function formatTs(ts) {
  170. const date = new Date(ts)
  171. return {
  172. YYYY: date.getFullYear(),
  173. MM: datePolyfill(date.getMonth() + 1),
  174. DD: datePolyfill(date.getDate()),
  175. HH: datePolyfill(date.getHours()),
  176. mm: datePolyfill(date.getMinutes()),
  177. ss: datePolyfill(date.getSeconds()),
  178. week: WEEK[date.getDay()]
  179. }
  180. }
  181. function datePolyfill(val) {
  182. return (val < 10 ? '0' + val : val) + ''
  183. }
  184. /**
  185. * 检测当前的小程序
  186. * 是否是最新版本,是否需要下载、更新
  187. */
  188. function checkUpdateVersion() {
  189. //判断微信版本是否 兼容小程序更新机制API的使用
  190. if (wx.canIUse('getUpdateManager')) {
  191. const updateManager = wx.getUpdateManager()
  192. //检测版本更新
  193. updateManager.onCheckForUpdate(function (res) {
  194. if (res.hasUpdate) {
  195. updateManager.onUpdateReady(function () {
  196. wx.showModal({
  197. title: '温馨提示',
  198. content: '检测到新版本,是否重启小程序?',
  199. showCancel: false,
  200. success: function (res) {
  201. if (res.confirm) {
  202. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  203. updateManager.applyUpdate()
  204. }
  205. }
  206. })
  207. })
  208. updateManager.onUpdateFailed(function () {
  209. // 新版本下载失败
  210. wx.showModal({
  211. title: '已有新版本',
  212. content: '请您删除小程序,重新搜索进入'
  213. })
  214. })
  215. }
  216. })
  217. } else {
  218. wx.showModal({
  219. title: '溫馨提示',
  220. content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
  221. })
  222. }
  223. }
  224. /**
  225. * 函数防抖
  226. * @param fn
  227. * @param wait
  228. * @param immediate
  229. * @returns {(function(...[*]=): void)|*}
  230. */
  231. function debounce(fn, wait = 1000, immediate = false) {
  232. let timer = null
  233. return function (...args) {
  234. const context = this
  235. if (timer) {
  236. clearTimeout(timer)
  237. }
  238. if (immediate && !timer) {
  239. fn.apply(context, args)
  240. }
  241. timer = setTimeout(() => {
  242. fn.apply(context, args)
  243. }, wait)
  244. }
  245. }
  246. function fen2Yuan(num) {
  247. return isNaN(num) ? '' : (num * 0.01).toFixed(2) * 1
  248. }
  249. function yuan2Fen(num) {
  250. if (isNaN(num)) {
  251. return ''
  252. }
  253. var amount = num.toString()
  254. var index = amount.indexOf('.')
  255. var arr = amount.split('.')
  256. var result = arr[0] * 100
  257. if (index > -1) {
  258. var temp = arr[1].split('')
  259. for (var i = 0; i < temp.length; i++) {
  260. if (i === 0) {
  261. result += temp[i] * 10
  262. } else {
  263. result += temp[i] * 1
  264. }
  265. }
  266. }
  267. return result
  268. }
  269. /**
  270. * 开始时间与耗时之间的日期详情
  271. * @param startTs
  272. * @param duration
  273. * @returns {[]|*[]}
  274. */
  275. function getDayList(startTs, duration) {
  276. const isStartTs = Object.prototype.toString.call(startTs) === '[object Number]'
  277. const isDuration = Object.prototype.toString.call(duration) === '[object Number]'
  278. if (!isStartTs || !isDuration) {
  279. return []
  280. }
  281. const result = []
  282. const hours = []
  283. const restTs = 3 * 3600 * 1000
  284. const start = formatTs(startTs)
  285. const startHour = start.HH * 1
  286. const polyfill = platform().ios ? '/' : '-'
  287. const YYYYMMDD = `${start.YYYY}${polyfill}${start.MM}${polyfill}${start.DD}`
  288. const startMax = new Date(`${YYYYMMDD} 23:59:59`).getTime()
  289. // 当天结束时间
  290. let endTs = startTs + duration
  291. // 当天结束时间
  292. let end = formatTs(endTs)
  293. let endHour = end.HH * 1
  294. // 大于当天23:59:59时
  295. if (endTs > startMax) {
  296. endTs = startMax
  297. end = formatTs(startMax)
  298. endHour = end.HH * 1
  299. // 计算剩余日期
  300. duration = duration - (startMax - startTs)
  301. } else {
  302. // 小于等于当天23:59:59时
  303. duration = 0
  304. }
  305. for (let i = startHour; i <= endHour; i++) {
  306. hours.push(i)
  307. }
  308. // 限行:高速2:00~5:00客车禁止通行
  309. if (hours.some(item => [2, 3, 4].findIndex(hour => hour === item) > -1)) {
  310. if (duration > 0) {
  311. duration += restTs
  312. } else {
  313. if (restTs + endTs <= startMax) {
  314. endTs = restTs + endTs
  315. end = formatTs(endTs)
  316. } else {
  317. duration = restTs - (startMax - endTs)
  318. end = formatTs(startMax)
  319. endTs = startMax
  320. }
  321. }
  322. }
  323. // 相差一分钟以上
  324. if (endTs - startTs >= 60000) {
  325. result.push({
  326. start,
  327. end,
  328. startTs,
  329. endTs,
  330. morThen22: endHour >= 22, // 关联住宿:是否跨过当天22:00
  331. duration
  332. })
  333. }
  334. if (duration <= 0) {
  335. return result
  336. }
  337. return result.concat(getDayList(endTs + 1000, duration - 1000))
  338. }
  339. function getTs(val, polyfill, type = 'ts') {
  340. const { ios } = platform()
  341. if (!val) {
  342. return 0
  343. }
  344. if (polyfill === 'YYYY年MM月DD日') {
  345. if (ios) {
  346. val = val.replace('年', '/').replace('月', '/').replace('日', '')
  347. } else {
  348. val = val.replace('年', '-').replace('月', '-').replace('日', '')
  349. }
  350. if (type === 's') {
  351. return Math.round(new Date(`${val} 00:00:00`).getTime() / 1000)
  352. }
  353. return new Date(`${val} 00:00:00`).getTime()
  354. }
  355. if (polyfill === 'YYYY-MM-DD') {
  356. if (ios) {
  357. val = val.replace(/-/g, '/')
  358. }
  359. if (type === 's') {
  360. return Math.round(new Date(`${val} 00:00:00`).getTime() / 1000)
  361. }
  362. return new Date(`${val} 00:00:00`).getTime()
  363. }
  364. return 0
  365. }
  366. module.exports = {
  367. platform,
  368. formatTime,
  369. formatArr,
  370. formatGlDate,
  371. cutDownTime,
  372. formatLocation,
  373. formatTs,
  374. checkUpdateVersion,
  375. debounce,
  376. toHideToast,
  377. fen2Yuan,
  378. yuan2Fen,
  379. getDayList,
  380. getTs
  381. }