util.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. import { base64_encode, base64_decode } from './base64';
  2. import md5 from './md5';
  3. var util = {};
  4. util.base64_encode = function (str) {
  5. return base64_encode(str)
  6. };
  7. util.base64_decode = function (str) {
  8. return base64_decode(str)
  9. };
  10. util.md5 = function (str) {
  11. return md5(str)
  12. };
  13. /**
  14. 构造微擎地址,
  15. @params action 微擎系统中的controller, action, do,格式为 'wxapp/home/navs'
  16. @params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
  17. */
  18. util.url = function (action, querystring) {
  19. var settingFile = getApp().globalData.siteInfo;
  20. var url = settingFile.siteroot + '?i=' + settingFile.uniacid + '&t=' + settingFile.multiid + '&v=' + settingFile.version + '&from=wxapp&';
  21. if (action) {
  22. action = action.split('/');
  23. if (action[0]) {
  24. url += 'c=' + action[0] + '&';
  25. }
  26. if (action[1]) {
  27. url += 'a=' + action[1] + '&';
  28. }
  29. if (action[2]) {
  30. url += 'do=' + action[2] + '&';
  31. }
  32. }
  33. if (querystring && typeof querystring === 'object') {
  34. for (let param in querystring) {
  35. if (param && querystring.hasOwnProperty(param) && querystring[param]) {
  36. url += param + '=' + querystring[param] + '&';
  37. }
  38. }
  39. }
  40. return url;
  41. }
  42. function getQuery(url) {
  43. var theRequest = [];
  44. if (url.indexOf("?") != -1) {
  45. var str = url.split('?')[1];
  46. var strs = str.split("&");
  47. for (var i = 0; i < strs.length; i++) {
  48. if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
  49. theRequest[i] = {
  50. 'name': strs[i].split("=")[0],
  51. 'value': unescape(strs[i].split("=")[1])
  52. }
  53. }
  54. }
  55. }
  56. return theRequest;
  57. }
  58. /*
  59. * 获取链接某个参数
  60. * url 链接地址
  61. * name 参数名称
  62. */
  63. function getUrlParam(url, name) {
  64. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  65. var r = url.split('?')[1].match(reg); //匹配目标参数
  66. if (r != null) return unescape(r[2]); return null; //返回参数值
  67. }
  68. /**
  69. * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
  70. * url 链接地址
  71. * date 参数{参数名1 : 值1, 参数名2 : 值2} *
  72. * token 签名token 非必须
  73. */
  74. function getSign(url, data, token) {
  75. var _ = require('./underscore.js');
  76. var md5 = require('./md5.js');
  77. var querystring = '';
  78. var sign = getUrlParam(url, 'sign');
  79. if (sign || (data && data.sign)) {
  80. return false;
  81. } else {
  82. if (url) {
  83. querystring = getQuery(url);
  84. }
  85. if (data) {
  86. var theRequest = [];
  87. for (let param in data) {
  88. if (param && data[param]) {
  89. theRequest = theRequest.concat({
  90. 'name': param,
  91. 'value': data[param]
  92. })
  93. }
  94. }
  95. querystring = querystring.concat(theRequest);
  96. }
  97. //排序
  98. querystring = _.sortBy(querystring, 'name');
  99. //去重
  100. querystring = _.uniq(querystring, true, 'name');
  101. var urlData = '';
  102. for (let i = 0; i < querystring.length; i++) {
  103. if (querystring[i] && querystring[i].name && querystring[i].value) {
  104. urlData += querystring[i].name + '=' + querystring[i].value;
  105. if (i < (querystring.length - 1)) {
  106. urlData += '&';
  107. }
  108. }
  109. }
  110. token = token ? token : '';
  111. sign = md5(urlData + token);
  112. return sign;
  113. }
  114. }
  115. util.getSign = function (url, data, token) {
  116. return getSign(url, data, token);
  117. };
  118. /**
  119. 二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合微擎格式化返回数据
  120. @params option 弹出参数表,
  121. {
  122. url : 同微信,
  123. data : 同微信,
  124. header : 同微信,
  125. method : 同微信,
  126. success : 同微信,
  127. fail : 同微信,
  128. complete : 同微信,
  129. cachetime : 缓存周期,在此周期内不重复请求http,默认不缓存
  130. }
  131. */
  132. util.request = function (option) {
  133. var _ = require('./underscore.js');
  134. var md5 = require('./md5.js');
  135. var app = getApp();
  136. var option = option ? option : {};
  137. option.cachetime = option.cachetime ? option.cachetime : 0;
  138. option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : true;
  139. var sessionid = wx.getStorageSync('userInfo').sessionid;
  140. var url = option.url;
  141. if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
  142. url = util.url(url);
  143. }
  144. var state = getUrlParam(url, 'state');
  145. if (!state && !(option.data && option.data.state) && sessionid) {
  146. url = url + '&state=we7sid-' + sessionid
  147. }
  148. if (!option.data || !option.data.m) {
  149. var nowPage = getCurrentPages();
  150. if (nowPage.length) {
  151. nowPage = nowPage[getCurrentPages().length - 1];
  152. if (nowPage && nowPage.__route__) {
  153. url = url + '&m=' + nowPage.__route__.split('/')[0];
  154. }
  155. }
  156. }
  157. var sign = getSign(url, option.data);
  158. if (sign) {
  159. url = url + "&sign=" + sign;
  160. }
  161. if (!url) {
  162. return false;
  163. }
  164. wx.showNavigationBarLoading();
  165. if (option.showLoading) {
  166. util.showLoading();
  167. }
  168. if (option.cachetime) {
  169. var cachekey = md5(url);
  170. var cachedata = wx.getStorageSync(cachekey);
  171. var timestamp = Date.parse(new Date());
  172. if (cachedata && cachedata.data) {
  173. if (cachedata.expire > timestamp) {
  174. if (option.complete && typeof option.complete == 'function') {
  175. option.complete(cachedata);
  176. }
  177. if (option.success && typeof option.success == 'function') {
  178. option.success(cachedata);
  179. }
  180. console.log('cache:' + url);
  181. wx.hideLoading();
  182. wx.hideNavigationBarLoading();
  183. return true;
  184. } else {
  185. wx.removeStorageSync(cachekey)
  186. }
  187. }
  188. }
  189. wx.request({
  190. 'url': url,
  191. 'data': option.data ? option.data : {},
  192. 'header': option.header ? option.header : {},
  193. 'method': option.method ? option.method : 'GET',
  194. 'header': {
  195. 'content-type': 'application/x-www-form-urlencoded'
  196. },
  197. 'success': function (response) {
  198. wx.hideNavigationBarLoading();
  199. wx.hideLoading();
  200. if (response.data.errno) {
  201. if (response.data.errno == '41009') {
  202. wx.setStorageSync('userInfo', '');
  203. util.getUserInfo(function () {
  204. util.request(option)
  205. });
  206. return;
  207. } else {
  208. if (option.fail && typeof option.fail == 'function') {
  209. option.fail(response);
  210. } else {
  211. if (response.data.message) {
  212. if (response.data.data != null && response.data.data.redirect) {
  213. var redirect = response.data.data.redirect;
  214. } else {
  215. var redirect = '';
  216. }
  217. app.util.message(response.data.message, redirect, 'error');
  218. }
  219. }
  220. return;
  221. }
  222. } else {
  223. if (option.success && typeof option.success == 'function') {
  224. option.success(response);
  225. }
  226. //写入缓存,减少HTTP请求,并且如果网络异常可以读取缓存数据
  227. if (option.cachetime) {
  228. var cachedata = { 'data': response.data, 'expire': timestamp + option.cachetime * 1000 };
  229. wx.setStorageSync(cachekey, cachedata);
  230. }
  231. }
  232. },
  233. 'fail': function (response) {
  234. wx.hideNavigationBarLoading();
  235. wx.hideLoading();
  236. //如果请求失败,尝试从缓存中读取数据
  237. var md5 = require('./md5.js');
  238. var cachekey = md5(url);
  239. var cachedata = wx.getStorageSync(cachekey);
  240. if (cachedata && cachedata.data) {
  241. if (option.success && typeof option.success == 'function') {
  242. option.success(cachedata);
  243. }
  244. console.log('failreadcache:' + url);
  245. return true;
  246. } else {
  247. if (option.fail && typeof option.fail == 'function') {
  248. option.fail(response);
  249. }
  250. }
  251. },
  252. 'complete': function (response) {
  253. // wx.hideNavigationBarLoading();
  254. // wx.hideLoading();
  255. if (option.complete && typeof option.complete == 'function') {
  256. option.complete(response);
  257. }
  258. }
  259. });
  260. }
  261. /*
  262. * 获取用户信息
  263. */
  264. util.getUserInfo = function (cb) {
  265. var login = function() {
  266. console.log('start login');
  267. var userInfo = {
  268. 'sessionid': '',
  269. 'wxInfo': '',
  270. 'memberInfo': '',
  271. };
  272. wx.login({
  273. success: function (res) {
  274. util.request({
  275. url: 'auth/session/openid',
  276. data: { code: res.code },
  277. cachetime: 0,
  278. success: function (session) {
  279. if (!session.data.errno) {
  280. userInfo.sessionid = session.data.data.sessionid
  281. wx.setStorageSync('userInfo', userInfo);
  282. wx.getUserInfo({
  283. success: function (wxInfo) {
  284. userInfo.wxInfo = wxInfo.userInfo
  285. wx.setStorageSync('userInfo', userInfo);
  286. util.request({
  287. url: 'auth/session/userinfo',
  288. data: {
  289. signature: wxInfo.signature,
  290. rawData: wxInfo.rawData,
  291. iv: wxInfo.iv,
  292. encryptedData: wxInfo.encryptedData
  293. },
  294. method: 'POST',
  295. header: {
  296. 'content-type': 'application/x-www-form-urlencoded'
  297. },
  298. cachetime: 0,
  299. success: function (res) {
  300. if (!res.data.errno) {
  301. userInfo.memberInfo = res.data.data;
  302. wx.setStorageSync('userInfo', userInfo);
  303. }
  304. typeof cb == "function" && cb(userInfo);
  305. }
  306. });
  307. },
  308. fail: function () {
  309. typeof cb == "function" && cb(userInfo);
  310. },
  311. complete: function () {
  312. }
  313. })
  314. }
  315. }
  316. });
  317. },
  318. fail: function () {
  319. wx.showModal({
  320. title: '获取信息失败',
  321. content: '请允许授权以便为您提供给服务',
  322. success: function (res) {
  323. if (res.confirm) {
  324. util.getUserInfo();
  325. }
  326. }
  327. })
  328. }
  329. });
  330. };
  331. var app = wx.getStorageSync('userInfo');
  332. if (app.sessionid) {
  333. wx.checkSession({
  334. success: function(){
  335. typeof cb == "function" && cb(app);
  336. },
  337. fail: function(){
  338. app.sessionid = '';
  339. console.log('relogin');
  340. wx.removeStorageSync('userInfo');
  341. login();
  342. }
  343. })
  344. } else {
  345. //调用登录接口
  346. login();
  347. }
  348. }
  349. util.navigateBack = function (obj) {
  350. let delta = obj.delta ? obj.delta : 1;
  351. if (obj.data) {
  352. let pages = getCurrentPages()
  353. let curPage = pages[pages.length - (delta + 1)];
  354. if (curPage.pageForResult) {
  355. curPage.pageForResult(obj.data);
  356. } else {
  357. curPage.setData(obj.data);
  358. }
  359. }
  360. wx.navigateBack({
  361. delta: delta, // 回退前 delta(默认为1) 页面
  362. success: function (res) {
  363. // success
  364. typeof obj.success == "function" && obj.success(res);
  365. },
  366. fail: function (err) {
  367. // fail
  368. typeof obj.fail == "function" && obj.fail(err);
  369. },
  370. complete: function () {
  371. // complete
  372. typeof obj.complete == "function" && obj.complete();
  373. }
  374. })
  375. };
  376. util.footer = function ($this) {
  377. let app = getApp();
  378. let that = $this;
  379. let tabBar = app.tabBar;
  380. for (let i in tabBar['list']) {
  381. tabBar['list'][i]['pageUrl'] = tabBar['list'][i]['pagePath'].replace(/(\?|#)[^"]*/g, '')
  382. }
  383. that.setData({
  384. tabBar: tabBar,
  385. 'tabBar.thisurl': that.__route__
  386. })
  387. };
  388. /*
  389. * 提示信息
  390. * type 为 success, error 当为 success, 时,为toast方式,否则为模态框的方式
  391. * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
  392. * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转,
  393. * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转,默认为 redirect
  394. */
  395. util.message = function(title, redirect, type) {
  396. if (!title) {
  397. return true;
  398. }
  399. if (typeof title == 'object') {
  400. redirect = title.redirect;
  401. type = title.type;
  402. title = title.title;
  403. }
  404. if (redirect) {
  405. var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
  406. if (redirectType == 'navigate:') {
  407. redirectFunction = 'navigateTo';
  408. url = redirect.substring(9);
  409. } else if (redirectType == 'redirect:') {
  410. redirectFunction = 'redirectTo';
  411. url = redirect.substring(9);
  412. } else {
  413. url = redirect;
  414. redirectFunction = 'redirectTo';
  415. }
  416. }
  417. console.log(url)
  418. if (!type) {
  419. type = 'success';
  420. }
  421. if (type == 'success') {
  422. wx.showToast({
  423. title: title,
  424. icon: 'success',
  425. duration: 2000,
  426. mask : url ? true : false,
  427. complete : function() {
  428. if (url) {
  429. setTimeout(function(){
  430. wx[redirectFunction]({
  431. url: url,
  432. });
  433. }, 1800);
  434. }
  435. }
  436. });
  437. } else if (type == 'error') {
  438. wx.showModal({
  439. title: '系统信息',
  440. content : title,
  441. showCancel : false,
  442. complete : function() {
  443. if (url) {
  444. wx[redirectFunction]({
  445. url: url,
  446. });
  447. }
  448. }
  449. });
  450. }
  451. }
  452. util.user = util.getUserInfo;
  453. //封装微信等待提示,防止ajax过多时,show多次
  454. util.showLoading = function() {
  455. var isShowLoading = wx.getStorageSync('isShowLoading');
  456. if (isShowLoading) {
  457. wx.hideLoading();
  458. wx.setStorageSync('isShowLoading', false);
  459. }
  460. wx.showLoading({
  461. title : '加载中',
  462. complete : function() {
  463. wx.setStorageSync('isShowLoading', true);
  464. },
  465. fail : function() {
  466. wx.setStorageSync('isShowLoading', false);
  467. }
  468. });
  469. }
  470. util.showImage = function(event) {
  471. var url = event ? event.currentTarget.dataset.preview : '';
  472. if (!url) {
  473. return false;
  474. }
  475. wx.previewImage({
  476. urls: [url]
  477. });
  478. }
  479. /**
  480. * 转换内容中的emoji表情为 unicode 码点,在Php中使用utf8_bytes来转换输出
  481. */
  482. util.parseContent = function(string) {
  483. if (!string) {
  484. return string;
  485. }
  486. var ranges = [
  487. '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
  488. '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
  489. '\ud83d[\ude80-\udeff]' // U+1F680 to U+1F6FF
  490. ];
  491. var emoji = string.match(
  492. new RegExp(ranges.join('|'), 'g'));
  493. if (emoji) {
  494. for (var i in emoji) {
  495. string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
  496. }
  497. }
  498. return string;
  499. }
  500. util.date = function(){
  501. /**
  502. * 判断闰年
  503. * @param date Date日期对象
  504. * @return boolean true 或false
  505. */
  506. this.isLeapYear = function(date){
  507. return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0)));
  508. }
  509. /**
  510. * 日期对象转换为指定格式的字符串
  511. * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
  512. * @param date Date日期对象, 如果缺省,则为当前时间
  513. *
  514. * YYYY/yyyy/YY/yy 表示年份
  515. * MM/M 月份
  516. * W/w 星期
  517. * dd/DD/d/D 日期
  518. * hh/HH/h/H 时间
  519. * mm/m 分钟
  520. * ss/SS/s/S 秒
  521. * @return string 指定格式的时间字符串
  522. */
  523. this.dateToStr = function(formatStr, date){
  524. formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
  525. date = arguments[1] || new Date();
  526. var str = formatStr;
  527. var Week = ['日','一','二','三','四','五','六'];
  528. str=str.replace(/yyyy|YYYY/,date.getFullYear());
  529. str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));
  530. str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));
  531. str=str.replace(/M/g,date.getMonth());
  532. str=str.replace(/w|W/g,Week[date.getDay()]);
  533. str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());
  534. str=str.replace(/d|D/g,date.getDate());
  535. str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());
  536. str=str.replace(/h|H/g,date.getHours());
  537. str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());
  538. str=str.replace(/m/g,date.getMinutes());
  539. str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());
  540. str=str.replace(/s|S/g,date.getSeconds());
  541. return str;
  542. }
  543. /**
  544. * 日期计算
  545. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  546. * @param num int
  547. * @param date Date 日期对象
  548. * @return Date 返回日期对象
  549. */
  550. this.dateAdd = function(strInterval, num, date){
  551. date = arguments[2] || new Date();
  552. switch (strInterval) {
  553. case 's' :return new Date(date.getTime() + (1000 * num));
  554. case 'n' :return new Date(date.getTime() + (60000 * num));
  555. case 'h' :return new Date(date.getTime() + (3600000 * num));
  556. case 'd' :return new Date(date.getTime() + (86400000 * num));
  557. case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));
  558. case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  559. case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  560. }
  561. }
  562. /**
  563. * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
  564. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  565. * @param dtStart Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  566. * @param dtEnd Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  567. */
  568. this.dateDiff = function(strInterval, dtStart, dtEnd) {
  569. switch (strInterval) {
  570. case 's' :return parseInt((dtEnd - dtStart) / 1000);
  571. case 'n' :return parseInt((dtEnd - dtStart) / 60000);
  572. case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
  573. case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
  574. case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
  575. case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
  576. case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
  577. }
  578. }
  579. /**
  580. * 字符串转换为日期对象 // eval 不可用
  581. * @param date Date 格式为yyyy-MM-dd HH:mm:ss,必须按年月日时分秒的顺序,中间分隔符不限制
  582. */
  583. this.strToDate = function(dateStr){
  584. var data = dateStr;
  585. var reCat = /(\d{1,4})/gm;
  586. var t = data.match(reCat);
  587. t[1] = t[1] - 1;
  588. eval('var d = new Date('+t.join(',')+');');
  589. return d;
  590. }
  591. /**
  592. * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
  593. *
  594. */
  595. this.strFormatToDate = function(formatStr, dateStr){
  596. var year = 0;
  597. var start = -1;
  598. var len = dateStr.length;
  599. if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
  600. year = dateStr.substr(start, 4);
  601. }
  602. var month = 0;
  603. if((start = formatStr.indexOf('MM')) > -1 && start < len){
  604. month = parseInt(dateStr.substr(start, 2)) - 1;
  605. }
  606. var day = 0;
  607. if((start = formatStr.indexOf('dd')) > -1 && start < len){
  608. day = parseInt(dateStr.substr(start, 2));
  609. }
  610. var hour = 0;
  611. if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
  612. hour = parseInt(dateStr.substr(start, 2));
  613. }
  614. var minute = 0;
  615. if((start = formatStr.indexOf('mm')) > -1 && start < len){
  616. minute = dateStr.substr(start, 2);
  617. }
  618. var second = 0;
  619. if((start = formatStr.indexOf('ss')) > -1 && start < len){
  620. second = dateStr.substr(start, 2);
  621. }
  622. return new Date(year, month, day, hour, minute, second);
  623. }
  624. /**
  625. * 日期对象转换为毫秒数
  626. */
  627. this.dateToLong = function(date){
  628. return date.getTime();
  629. }
  630. /**
  631. * 毫秒转换为日期对象
  632. * @param dateVal number 日期的毫秒数
  633. */
  634. this.longToDate = function(dateVal){
  635. return new Date(dateVal);
  636. }
  637. /**
  638. * 判断字符串是否为日期格式
  639. * @param str string 字符串
  640. * @param formatStr string 日期格式, 如下 yyyy-MM-dd
  641. */
  642. this.isDate = function(str, formatStr){
  643. if (formatStr == null){
  644. formatStr = "yyyyMMdd";
  645. }
  646. var yIndex = formatStr.indexOf("yyyy");
  647. if(yIndex==-1){
  648. return false;
  649. }
  650. var year = str.substring(yIndex,yIndex+4);
  651. var mIndex = formatStr.indexOf("MM");
  652. if(mIndex==-1){
  653. return false;
  654. }
  655. var month = str.substring(mIndex,mIndex+2);
  656. var dIndex = formatStr.indexOf("dd");
  657. if(dIndex==-1){
  658. return false;
  659. }
  660. var day = str.substring(dIndex,dIndex+2);
  661. if(!isNumber(year)||year>"2100" || year< "1900"){
  662. return false;
  663. }
  664. if(!isNumber(month)||month>"12" || month< "01"){
  665. return false;
  666. }
  667. if(day>getMaxDay(year,month) || day< "01"){
  668. return false;
  669. }
  670. return true;
  671. }
  672. this.getMaxDay = function(year,month) {
  673. if(month==4||month==6||month==9||month==11)
  674. return "30";
  675. if(month==2)
  676. if(year%4==0&&year%100!=0 || year%400==0)
  677. return "29";
  678. else
  679. return "28";
  680. return "31";
  681. }
  682. /**
  683. * 变量是否为数字
  684. */
  685. this.isNumber = function(str)
  686. {
  687. var regExp = /^\d+$/g;
  688. return regExp.test(str);
  689. }
  690. /**
  691. * 把日期分割成数组 [年、月、日、时、分、秒]
  692. */
  693. this.toArray = function(myDate)
  694. {
  695. myDate = arguments[0] || new Date();
  696. var myArray = Array();
  697. myArray[0] = myDate.getFullYear();
  698. myArray[1] = myDate.getMonth();
  699. myArray[2] = myDate.getDate();
  700. myArray[3] = myDate.getHours();
  701. myArray[4] = myDate.getMinutes();
  702. myArray[5] = myDate.getSeconds();
  703. return myArray;
  704. }
  705. /**
  706. * 取得日期数据信息
  707. * 参数 interval 表示数据类型
  708. * y 年 M月 d日 w星期 ww周 h时 n分 s秒
  709. */
  710. this.datePart = function(interval, myDate)
  711. {
  712. myDate = arguments[1] || new Date();
  713. var partStr='';
  714. var Week = ['日','一','二','三','四','五','六'];
  715. switch (interval)
  716. {
  717. case 'y' :partStr = myDate.getFullYear();break;
  718. case 'M' :partStr = myDate.getMonth()+1;break;
  719. case 'd' :partStr = myDate.getDate();break;
  720. case 'w' :partStr = Week[myDate.getDay()];break;
  721. case 'ww' :partStr = myDate.WeekNumOfYear();break;
  722. case 'h' :partStr = myDate.getHours();break;
  723. case 'm' :partStr = myDate.getMinutes();break;
  724. case 's' :partStr = myDate.getSeconds();break;
  725. }
  726. return partStr;
  727. }
  728. /**
  729. * 取得当前日期所在月的最大天数
  730. */
  731. this.maxDayOfDate = function(date)
  732. {
  733. date = arguments[0] || new Date();
  734. date.setDate(1);
  735. date.setMonth(date.getMonth() + 1);
  736. var time = date.getTime() - 24 * 60 * 60 * 1000;
  737. var newDate = new Date(time);
  738. return newDate.getDate();
  739. }
  740. };
  741. module.exports = util;