util.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. uni.setStorageSync('userInfo', '');
  204. util.getUserInfo(function () {
  205. util.request(option)
  206. });
  207. return;
  208. } else {
  209. if (option.fail && typeof option.fail == 'function') {
  210. option.fail(response);
  211. } else {
  212. if (response.data.message) {
  213. if (response.data.data != null && response.data.data.redirect) {
  214. var redirect = response.data.data.redirect;
  215. } else {
  216. var redirect = '';
  217. }
  218. app.util.message(response.data.message, redirect, 'error');
  219. }
  220. }
  221. return;
  222. }
  223. } else {
  224. if (option.success && typeof option.success == 'function') {
  225. option.success(response);
  226. }
  227. //写入缓存,减少HTTP请求,并且如果网络异常可以读取缓存数据
  228. if (option.cachetime) {
  229. var cachedata = { 'data': response.data, 'expire': timestamp + option.cachetime * 1000 };
  230. wx.setStorageSync(cachekey, cachedata);
  231. }
  232. }
  233. },
  234. 'fail': function (response) {
  235. wx.hideNavigationBarLoading();
  236. wx.hideLoading();
  237. //如果请求失败,尝试从缓存中读取数据
  238. var md5 = require('./md5.js');
  239. var cachekey = md5(url);
  240. var cachedata = wx.getStorageSync(cachekey);
  241. if (cachedata && cachedata.data) {
  242. if (option.success && typeof option.success == 'function') {
  243. option.success(cachedata);
  244. }
  245. console.log('failreadcache:' + url);
  246. return true;
  247. } else {
  248. if (option.fail && typeof option.fail == 'function') {
  249. option.fail(response);
  250. }
  251. }
  252. },
  253. 'complete': function (response) {
  254. // wx.hideNavigationBarLoading();
  255. // wx.hideLoading();
  256. if (option.complete && typeof option.complete == 'function') {
  257. option.complete(response);
  258. }
  259. }
  260. });
  261. }
  262. /*
  263. * 获取用户信息
  264. */
  265. util.getUserInfo = function (cb) {
  266. var login = function() {
  267. console.log('start login');
  268. var userInfo = {
  269. 'sessionid': '',
  270. 'wxInfo': '',
  271. 'memberInfo': '',
  272. };
  273. wx.login({
  274. success: function (res) {
  275. util.request({
  276. url: 'auth/session/openid',
  277. data: { code: res.code },
  278. cachetime: 0,
  279. success: function (session) {
  280. if (!session.data.errno) {
  281. userInfo.sessionid = session.data.data.sessionid
  282. wx.setStorageSync('userInfo', userInfo);
  283. uni.setStorageSync('userInfo', userInfo);
  284. wx.getUserInfo({
  285. success: function (wxInfo) {
  286. userInfo.wxInfo = wxInfo.userInfo
  287. wx.setStorageSync('userInfo', userInfo);
  288. uni.setStorageSync('userInfo', userInfo);
  289. util.request({
  290. url: 'auth/session/userinfo',
  291. data: {
  292. signature: wxInfo.signature,
  293. rawData: wxInfo.rawData,
  294. iv: wxInfo.iv,
  295. encryptedData: wxInfo.encryptedData
  296. },
  297. method: 'POST',
  298. header: {
  299. 'content-type': 'application/x-www-form-urlencoded'
  300. },
  301. cachetime: 0,
  302. success: function (res) {
  303. if (!res.data.errno) {
  304. userInfo.memberInfo = res.data.data;
  305. wx.setStorageSync('userInfo', userInfo);
  306. uni.setStorageSync('userInfo', userInfo);
  307. }
  308. typeof cb == "function" && cb(userInfo);
  309. }
  310. });
  311. },
  312. fail: function () {
  313. typeof cb == "function" && cb(userInfo);
  314. },
  315. complete: function () {
  316. }
  317. })
  318. }
  319. }
  320. });
  321. },
  322. fail: function () {
  323. wx.showModal({
  324. title: '获取信息失败',
  325. content: '请允许授权以便为您提供给服务',
  326. success: function (res) {
  327. if (res.confirm) {
  328. util.getUserInfo();
  329. }
  330. }
  331. })
  332. }
  333. });
  334. };
  335. var app = wx.getStorageSync('userInfo');
  336. if (app.sessionid) {
  337. wx.checkSession({
  338. success: function(){
  339. typeof cb == "function" && cb(app);
  340. },
  341. fail: function(){
  342. app.sessionid = '';
  343. console.log('relogin');
  344. wx.removeStorageSync('userInfo');
  345. login();
  346. }
  347. })
  348. } else {
  349. //调用登录接口
  350. login();
  351. }
  352. }
  353. util.navigateBack = function (obj) {
  354. let delta = obj.delta ? obj.delta : 1;
  355. if (obj.data) {
  356. let pages = getCurrentPages()
  357. let curPage = pages[pages.length - (delta + 1)];
  358. if (curPage.pageForResult) {
  359. curPage.pageForResult(obj.data);
  360. } else {
  361. curPage.setData(obj.data);
  362. }
  363. }
  364. wx.navigateBack({
  365. delta: delta, // 回退前 delta(默认为1) 页面
  366. success: function (res) {
  367. // success
  368. typeof obj.success == "function" && obj.success(res);
  369. },
  370. fail: function (err) {
  371. // fail
  372. typeof obj.fail == "function" && obj.fail(err);
  373. },
  374. complete: function () {
  375. // complete
  376. typeof obj.complete == "function" && obj.complete();
  377. }
  378. })
  379. };
  380. util.footer = function ($this) {
  381. let app = getApp();
  382. let that = $this;
  383. let tabBar = app.tabBar;
  384. for (let i in tabBar['list']) {
  385. tabBar['list'][i]['pageUrl'] = tabBar['list'][i]['pagePath'].replace(/(\?|#)[^"]*/g, '')
  386. }
  387. that.setData({
  388. tabBar: tabBar,
  389. 'tabBar.thisurl': that.__route__
  390. })
  391. };
  392. /*
  393. * 提示信息
  394. * type 为 success, error 当为 success, 时,为toast方式,否则为模态框的方式
  395. * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
  396. * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转,
  397. * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转,默认为 redirect
  398. */
  399. util.message = function(title, redirect, type) {
  400. if (!title) {
  401. return true;
  402. }
  403. if (typeof title == 'object') {
  404. redirect = title.redirect;
  405. type = title.type;
  406. title = title.title;
  407. }
  408. if (redirect) {
  409. var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
  410. if (redirectType == 'navigate:') {
  411. redirectFunction = 'navigateTo';
  412. url = redirect.substring(9);
  413. } else if (redirectType == 'redirect:') {
  414. redirectFunction = 'redirectTo';
  415. url = redirect.substring(9);
  416. } else {
  417. url = redirect;
  418. redirectFunction = 'redirectTo';
  419. }
  420. }
  421. console.log(url)
  422. if (!type) {
  423. type = 'success';
  424. }
  425. if (type == 'success') {
  426. wx.showToast({
  427. title: title,
  428. icon: 'success',
  429. duration: 2000,
  430. mask : url ? true : false,
  431. complete : function() {
  432. if (url) {
  433. setTimeout(function(){
  434. wx[redirectFunction]({
  435. url: url,
  436. });
  437. }, 1800);
  438. }
  439. }
  440. });
  441. } else if (type == 'error') {
  442. wx.showModal({
  443. title: '系统信息',
  444. content : title,
  445. showCancel : false,
  446. complete : function() {
  447. if (url) {
  448. wx[redirectFunction]({
  449. url: url,
  450. });
  451. }
  452. }
  453. });
  454. }
  455. }
  456. util.user = util.getUserInfo;
  457. //封装微信等待提示,防止ajax过多时,show多次
  458. util.showLoading = function() {
  459. var isShowLoading = wx.getStorageSync('isShowLoading');
  460. if (isShowLoading) {
  461. wx.hideLoading();
  462. wx.setStorageSync('isShowLoading', false);
  463. }
  464. wx.showLoading({
  465. title : '加载中',
  466. complete : function() {
  467. wx.setStorageSync('isShowLoading', true);
  468. },
  469. fail : function() {
  470. wx.setStorageSync('isShowLoading', false);
  471. }
  472. });
  473. }
  474. util.showImage = function(event) {
  475. var url = event ? event.currentTarget.dataset.preview : '';
  476. if (!url) {
  477. return false;
  478. }
  479. wx.previewImage({
  480. urls: [url]
  481. });
  482. }
  483. /**
  484. * 转换内容中的emoji表情为 unicode 码点,在Php中使用utf8_bytes来转换输出
  485. */
  486. util.parseContent = function(string) {
  487. if (!string) {
  488. return string;
  489. }
  490. var ranges = [
  491. '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
  492. '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
  493. '\ud83d[\ude80-\udeff]' // U+1F680 to U+1F6FF
  494. ];
  495. var emoji = string.match(
  496. new RegExp(ranges.join('|'), 'g'));
  497. if (emoji) {
  498. for (var i in emoji) {
  499. string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
  500. }
  501. }
  502. return string;
  503. }
  504. util.date = function(){
  505. /**
  506. * 判断闰年
  507. * @param date Date日期对象
  508. * @return boolean true 或false
  509. */
  510. this.isLeapYear = function(date){
  511. return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0)));
  512. }
  513. /**
  514. * 日期对象转换为指定格式的字符串
  515. * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
  516. * @param date Date日期对象, 如果缺省,则为当前时间
  517. *
  518. * YYYY/yyyy/YY/yy 表示年份
  519. * MM/M 月份
  520. * W/w 星期
  521. * dd/DD/d/D 日期
  522. * hh/HH/h/H 时间
  523. * mm/m 分钟
  524. * ss/SS/s/S 秒
  525. * @return string 指定格式的时间字符串
  526. */
  527. this.dateToStr = function(formatStr, date){
  528. formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
  529. date = arguments[1] || new Date();
  530. var str = formatStr;
  531. var Week = ['日','一','二','三','四','五','六'];
  532. str=str.replace(/yyyy|YYYY/,date.getFullYear());
  533. str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));
  534. str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));
  535. str=str.replace(/M/g,date.getMonth());
  536. str=str.replace(/w|W/g,Week[date.getDay()]);
  537. str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());
  538. str=str.replace(/d|D/g,date.getDate());
  539. str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());
  540. str=str.replace(/h|H/g,date.getHours());
  541. str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());
  542. str=str.replace(/m/g,date.getMinutes());
  543. str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());
  544. str=str.replace(/s|S/g,date.getSeconds());
  545. return str;
  546. }
  547. /**
  548. * 日期计算
  549. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  550. * @param num int
  551. * @param date Date 日期对象
  552. * @return Date 返回日期对象
  553. */
  554. this.dateAdd = function(strInterval, num, date){
  555. date = arguments[2] || new Date();
  556. switch (strInterval) {
  557. case 's' :return new Date(date.getTime() + (1000 * num));
  558. case 'n' :return new Date(date.getTime() + (60000 * num));
  559. case 'h' :return new Date(date.getTime() + (3600000 * num));
  560. case 'd' :return new Date(date.getTime() + (86400000 * num));
  561. case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));
  562. case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  563. case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
  564. }
  565. }
  566. /**
  567. * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
  568. * @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  569. * @param dtStart Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  570. * @param dtEnd Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  571. */
  572. this.dateDiff = function(strInterval, dtStart, dtEnd) {
  573. switch (strInterval) {
  574. case 's' :return parseInt((dtEnd - dtStart) / 1000);
  575. case 'n' :return parseInt((dtEnd - dtStart) / 60000);
  576. case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
  577. case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
  578. case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
  579. case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
  580. case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
  581. }
  582. }
  583. /**
  584. * 字符串转换为日期对象 // eval 不可用
  585. * @param date Date 格式为yyyy-MM-dd HH:mm:ss,必须按年月日时分秒的顺序,中间分隔符不限制
  586. */
  587. this.strToDate = function(dateStr){
  588. var data = dateStr;
  589. var reCat = /(\d{1,4})/gm;
  590. var t = data.match(reCat);
  591. t[1] = t[1] - 1;
  592. eval('var d = new Date('+t.join(',')+');');
  593. return d;
  594. }
  595. /**
  596. * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
  597. *
  598. */
  599. this.strFormatToDate = function(formatStr, dateStr){
  600. var year = 0;
  601. var start = -1;
  602. var len = dateStr.length;
  603. if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
  604. year = dateStr.substr(start, 4);
  605. }
  606. var month = 0;
  607. if((start = formatStr.indexOf('MM')) > -1 && start < len){
  608. month = parseInt(dateStr.substr(start, 2)) - 1;
  609. }
  610. var day = 0;
  611. if((start = formatStr.indexOf('dd')) > -1 && start < len){
  612. day = parseInt(dateStr.substr(start, 2));
  613. }
  614. var hour = 0;
  615. if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
  616. hour = parseInt(dateStr.substr(start, 2));
  617. }
  618. var minute = 0;
  619. if((start = formatStr.indexOf('mm')) > -1 && start < len){
  620. minute = dateStr.substr(start, 2);
  621. }
  622. var second = 0;
  623. if((start = formatStr.indexOf('ss')) > -1 && start < len){
  624. second = dateStr.substr(start, 2);
  625. }
  626. return new Date(year, month, day, hour, minute, second);
  627. }
  628. /**
  629. * 日期对象转换为毫秒数
  630. */
  631. this.dateToLong = function(date){
  632. return date.getTime();
  633. }
  634. /**
  635. * 毫秒转换为日期对象
  636. * @param dateVal number 日期的毫秒数
  637. */
  638. this.longToDate = function(dateVal){
  639. return new Date(dateVal);
  640. }
  641. /**
  642. * 判断字符串是否为日期格式
  643. * @param str string 字符串
  644. * @param formatStr string 日期格式, 如下 yyyy-MM-dd
  645. */
  646. this.isDate = function(str, formatStr){
  647. if (formatStr == null){
  648. formatStr = "yyyyMMdd";
  649. }
  650. var yIndex = formatStr.indexOf("yyyy");
  651. if(yIndex==-1){
  652. return false;
  653. }
  654. var year = str.substring(yIndex,yIndex+4);
  655. var mIndex = formatStr.indexOf("MM");
  656. if(mIndex==-1){
  657. return false;
  658. }
  659. var month = str.substring(mIndex,mIndex+2);
  660. var dIndex = formatStr.indexOf("dd");
  661. if(dIndex==-1){
  662. return false;
  663. }
  664. var day = str.substring(dIndex,dIndex+2);
  665. if(!isNumber(year)||year>"2100" || year< "1900"){
  666. return false;
  667. }
  668. if(!isNumber(month)||month>"12" || month< "01"){
  669. return false;
  670. }
  671. if(day>getMaxDay(year,month) || day< "01"){
  672. return false;
  673. }
  674. return true;
  675. }
  676. this.getMaxDay = function(year,month) {
  677. if(month==4||month==6||month==9||month==11)
  678. return "30";
  679. if(month==2)
  680. if(year%4==0&&year%100!=0 || year%400==0)
  681. return "29";
  682. else
  683. return "28";
  684. return "31";
  685. }
  686. /**
  687. * 变量是否为数字
  688. */
  689. this.isNumber = function(str)
  690. {
  691. var regExp = /^\d+$/g;
  692. return regExp.test(str);
  693. }
  694. /**
  695. * 把日期分割成数组 [年、月、日、时、分、秒]
  696. */
  697. this.toArray = function(myDate)
  698. {
  699. myDate = arguments[0] || new Date();
  700. var myArray = Array();
  701. myArray[0] = myDate.getFullYear();
  702. myArray[1] = myDate.getMonth();
  703. myArray[2] = myDate.getDate();
  704. myArray[3] = myDate.getHours();
  705. myArray[4] = myDate.getMinutes();
  706. myArray[5] = myDate.getSeconds();
  707. return myArray;
  708. }
  709. /**
  710. * 取得日期数据信息
  711. * 参数 interval 表示数据类型
  712. * y 年 M月 d日 w星期 ww周 h时 n分 s秒
  713. */
  714. this.datePart = function(interval, myDate)
  715. {
  716. myDate = arguments[1] || new Date();
  717. var partStr='';
  718. var Week = ['日','一','二','三','四','五','六'];
  719. switch (interval)
  720. {
  721. case 'y' :partStr = myDate.getFullYear();break;
  722. case 'M' :partStr = myDate.getMonth()+1;break;
  723. case 'd' :partStr = myDate.getDate();break;
  724. case 'w' :partStr = Week[myDate.getDay()];break;
  725. case 'ww' :partStr = myDate.WeekNumOfYear();break;
  726. case 'h' :partStr = myDate.getHours();break;
  727. case 'm' :partStr = myDate.getMinutes();break;
  728. case 's' :partStr = myDate.getSeconds();break;
  729. }
  730. return partStr;
  731. }
  732. /**
  733. * 取得当前日期所在月的最大天数
  734. */
  735. this.maxDayOfDate = function(date)
  736. {
  737. date = arguments[0] || new Date();
  738. date.setDate(1);
  739. date.setMonth(date.getMonth() + 1);
  740. var time = date.getTime() - 24 * 60 * 60 * 1000;
  741. var newDate = new Date(time);
  742. return newDate.getDate();
  743. }
  744. };
  745. module.exports = util;