util.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { config } from "../config/config"
  2. import { log } from "./log"
  3. import { tools } from "./tools"
  4. export class util {
  5. /**
  6. * 获取本地数据
  7. */
  8. public static getStorage(key:string){
  9. try {
  10. let d = uni.getStorageSync(key)
  11. if(util.isNull(d)){
  12. return null
  13. }
  14. return d
  15. } catch(e) {
  16. console.error('本地获取失败', e);
  17. return null
  18. }
  19. }
  20. /**
  21. * 设置本地数据
  22. */
  23. public static setStorage(key:string,value:string){
  24. try {
  25. uni.setStorageSync(key,value)
  26. } catch (e) {
  27. console.error('本地存储失败', e);
  28. }
  29. }
  30. /**
  31. * 删除本地key数据
  32. */
  33. public static removeStorageForKey(key:string){
  34. try {
  35. uni.removeStorageSync(key)
  36. } catch (e) {
  37. console.error('本地删除失败', e);
  38. }
  39. }
  40. /**
  41. * 清除本地数据
  42. */
  43. public static clearAllStorage(){
  44. try {
  45. uni.clearStorageSync()
  46. } catch (e) {
  47. console.error('本地清空失败', e);
  48. }
  49. }
  50. public static isNull(v:any){
  51. if(v==null||v==undefined||v==""){
  52. return true
  53. }
  54. return false
  55. }
  56. public static alert(v:string){
  57. let Platform = tools.getCurPlatform()
  58. if(Platform==config.Platform.H5){
  59. alert(v)
  60. }else if(Platform==config.Platform.TOUTIAO){
  61. log.Debug("TOUTIAO",v)
  62. }else if(Platform==config.Platform.WEIXIN){
  63. log.Debug("WEIXIN",v)
  64. }
  65. }
  66. // Loadding
  67. public static showLoading(title='加载中...',mask:boolean=false) {
  68. if(title.length==0) {
  69. title = '加载中...'
  70. }
  71. uni.showLoading({
  72. title:title,
  73. mask:mask
  74. })
  75. }
  76. // delaytime:毫秒
  77. public static hideLoading(delaytime:number=0, cb:Function=null) {
  78. if(delaytime<=0) {
  79. uni.hideLoading()
  80. cb && cb()
  81. return
  82. }
  83. setTimeout(()=>{
  84. uni.hideLoading()
  85. cb && cb()
  86. },delaytime)
  87. }
  88. // Toast
  89. public static showInfoToast(title:string,duration=1500,mask=false) {
  90. uni.showToast({
  91. title:title,
  92. icon:'none',
  93. duration:duration,
  94. mask:mask
  95. })
  96. }
  97. public static showSuccessToast(title:string,duration=1500,mask=false) {
  98. uni.showToast({
  99. title:title,
  100. icon:'success',
  101. duration:duration,
  102. mask:mask
  103. })
  104. }
  105. public static showErrorToast(title:string,duration=1500,mask=false) {
  106. uni.showToast({
  107. title:title,
  108. icon:'error',
  109. duration:duration,
  110. mask:mask
  111. })
  112. }
  113. // Modal
  114. public static showModal(title:string, content:string, confirm_cb:Function=null, cancel_cb:Function=null, confirmText:string='确定', showCancel:boolean=true, cancelText:string='取消') {
  115. uni.showModal({
  116. title: title,
  117. content: content,
  118. confirmText: confirmText,
  119. showCancel: showCancel,
  120. cancelText: cancelText,
  121. success: function (res) {
  122. if (res.confirm) {
  123. // console.log('用户点击确定')
  124. confirm_cb && confirm_cb()
  125. } else if (res.cancel) {
  126. // console.log('用户点击取消')
  127. cancel_cb && cancel_cb()
  128. }
  129. }
  130. })
  131. }
  132. public static showModalNoCancel(title:string, content:string, confirm_cb:Function=null, cancel_cb:Function=null, confirmText:string='确定'){
  133. this.showModal(title,content,confirm_cb,cancel_cb,confirmText,false)
  134. }
  135. // ActionSheet
  136. public static showActionSheet(alertText:string, itemList:string[], confirm_cb:Function, cancel_cb:Function=null) {
  137. uni.showActionSheet({
  138. alertText:alertText,
  139. itemList: itemList,
  140. success: function (res) {
  141. // console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
  142. confirm_cb && confirm_cb(res.tapIndex)
  143. },
  144. fail: function (err) {
  145. // console.log('showActionSheet err=',err.errMsg);
  146. cancel_cb && cancel_cb()
  147. }
  148. });
  149. }
  150. /**
  151. * 格式化时间
  152. * dateTime(String|Number) 需要格式化的时间戳
  153. * formatStr(String) 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
  154. */
  155. public static timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
  156. let date:any
  157. // 若传入时间为假值,则取当前时间
  158. if (!dateTime) {
  159. date = new Date()
  160. }
  161. // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容)
  162. else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
  163. date = new Date(dateTime * 1000)
  164. }
  165. // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
  166. else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
  167. date = new Date(Number(dateTime))
  168. }
  169. // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
  170. // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
  171. else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
  172. date = new Date(dateTime.replace(/-/g, '/'))
  173. }
  174. // 其他都认为符合 RFC 2822 规范
  175. else {
  176. date = new Date(dateTime)
  177. }
  178. const timeSource = {
  179. 'y': date.getFullYear().toString(), // 年
  180. 'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
  181. 'd': date.getDate().toString().padStart(2, '0'), // 日
  182. 'h': date.getHours().toString().padStart(2, '0'), // 时
  183. 'M': date.getMinutes().toString().padStart(2, '0'), // 分
  184. 's': date.getSeconds().toString().padStart(2, '0') // 秒
  185. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  186. }
  187. for (const key in timeSource) {
  188. const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
  189. if (ret) {
  190. // 年可能只需展示两位
  191. const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
  192. formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
  193. }
  194. }
  195. return formatStr
  196. }
  197. // 转换时间(timeStamp:毫秒)
  198. public static convertTimeString (timeStamp:number) {
  199. if (timeStamp <= 0) {
  200. return ""
  201. }
  202. let nowTimeDate = new Date()
  203. let nowTimeStamp = nowTimeDate.getTime()
  204. // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  205. if (timeStamp.toString().length == 10) timeStamp *= 1000
  206. let between = (nowTimeStamp - timeStamp)/1000 //转换秒
  207. // console.log('between=',between,'timeStamp=',timeStamp,'nowTimeStamp=',nowTimeStamp)
  208. if (between < 300) {
  209. return "刚刚"
  210. } else if (between >= 300 && between < 3600) {
  211. return `${Math.round(between/60)}分钟前`
  212. } else if (between >= 3600 && between < 86400) {
  213. return `${Math.round(between/3600)}小时前`
  214. } else if (between >= 86400 && between < 86400 * 2) {
  215. return "昨天"
  216. } else if (between >= 86400 * 2 && between < 86400 * 30) {
  217. return `${Math.round(between/86400)}天前`
  218. } else {
  219. return util.timeFormat(timeStamp)
  220. }
  221. }
  222. // 转换单位
  223. public static convertUnit(arg:number) {
  224. let realVal = arg+''
  225. if(arg.toString().length>=4) {
  226. let number = arg/10000
  227. realVal = number.toFixed(1) + '万'
  228. }
  229. return realVal
  230. }
  231. // 去除空格
  232. public static trim(str:string, pos = 'both') {
  233. str = String(str)
  234. if (pos == 'both') {
  235. return str.replace(/^\s+|\s+$/g, '')
  236. }
  237. if (pos == 'left') {
  238. return str.replace(/^\s*/, '')
  239. }
  240. if (pos == 'right') {
  241. return str.replace(/(\s*$)/g, '')
  242. }
  243. if (pos == 'all') {
  244. return str.replace(/\s+/g, '')
  245. }
  246. return str
  247. }
  248. public static reLaunch(url:string){
  249. uni.reLaunch({
  250. url:url
  251. })
  252. }
  253. }