utils-time.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /**
  2. * 工具类 - 时间相关
  3. * @module js/utils-time
  4. * @description 常用时间工具方法集合
  5. * @author liu_yang17<liu_yang17@dahuatech.com>
  6. * @version 7.02
  7. */
  8. Date.prototype.format = function (format) {
  9. let format1 = format;
  10. var o = {
  11. "M+": this.getMonth() + 1,
  12. "d+": this.getDate(),
  13. "H+": this.getHours(),
  14. "m+": this.getMinutes(),
  15. "s+": this.getSeconds(),
  16. "q+": Math.floor((this.getMonth() + 3) / 3),
  17. "S+": this.getMilliseconds()
  18. };
  19. if (!format1) {
  20. format1 = "yyyy-MM-dd";
  21. }
  22. if (/(y+)/.test(format1)) {
  23. format1 = format1.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  24. }
  25. if (/(S+)/.test(format1)) {
  26. format1 = format1.replace(RegExp.$1, (this.getMilliseconds() + "").substr(3 - RegExp.$1.length));
  27. }
  28. for (var k in o) {
  29. if (new RegExp("(" + k + ")").test(format1)) {
  30. format1 = format1.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  31. }
  32. }
  33. return format1;
  34. }
  35. var REG = {
  36. TIME: /^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,
  37. DATE: /^\d{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[0-1]) ([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,
  38. DATE_M_D_Y: /^(0[0-9]|1[0-2])-([0-2][0-9]|3[0-1])-\d{4} ([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,
  39. DATE_Z: /^\d{4}(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])T([0-1][0-9]|2[0-3])[0-5][0-9][0-5][0-9]Z$/,
  40. DATE_Z_S: /^\d{4}(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])T([0-1][0-9]|2[0-3])[0-5][0-9][0-5][0-9][.]\d{0,3}Z$/
  41. }
  42. /**
  43. * add Zero 月日时分秒补0函数
  44. */
  45. function addZero(time) {
  46. let newTime = time > 9 ? time : '0' + time
  47. return newTime
  48. }
  49. /**
  50. * 校验时间格式
  51. * @param {string} time 时间格式,如 10:00:00
  52. */
  53. function valifyTime(time) {
  54. const reg = /^\d{2}:\d{2}:\d{2}$/
  55. return reg.test(time)
  56. }
  57. /**
  58. * 判定两组时间序列是否存在重复(交叉或包含)
  59. * @param {array} time1Arr 时间范围,如 [10:00:00, 12:00:00]
  60. * @param {array} time2Arr 时间范围,如 [09:00:00, 23:00:00]
  61. */
  62. function isTimeContainTime(time1Arr, time2Arr) {
  63. let timeArr
  64. let validate = true
  65. // 确保两组时间范围格式正确
  66. if (!Array.isArray(time1Arr) || !Array.isArray(time2Arr)) {
  67. throw new Error('Please enter two array.')
  68. }
  69. if (time1Arr.length !== 2 || time2Arr.length !== 2) {
  70. throw new Error('Please enter currect time.')
  71. }
  72. timeArr = [...time1Arr, ...time2Arr]
  73. for (let time of timeArr) {
  74. if (!valifyTime(time)) {
  75. throw new Error('Please enter currect time.')
  76. }
  77. }
  78. // 检验时间是否存在重复
  79. if (time2Arr[0] > time1Arr[0] && time2Arr[0] < time1Arr[1] ||
  80. time2Arr[1] > time1Arr[0] && time2Arr[1] < time1Arr[1]) {
  81. validate = false;
  82. }
  83. if (time1Arr[0] > time2Arr[0] && time1Arr[0] < time2Arr[1] ||
  84. time1Arr[1] > time2Arr[0] && time1Arr[1] < time2Arr[1]) {
  85. validate = false;
  86. }
  87. return validate
  88. }
  89. /**
  90. * 将时间转换为UTC时间字符串,支持格式 hh:mm:ss
  91. * @description 按源格式返回
  92. * @param {string} timeStr 源时间
  93. * @returns {object} 包含time和日期偏差
  94. */
  95. function toISOStringByTime(timeStr) {
  96. const time = {}
  97. let date = new Date(`2000/10/24 ${timeStr}`)
  98. time.d = date.getUTCDate()
  99. time.h = addZero(date.getUTCHours())
  100. time.min = addZero(date.getUTCMinutes())
  101. time.s = addZero(date.getUTCSeconds())
  102. return {
  103. offset: time.d - 24,
  104. time: `${time.h}:${time.min}:${time.s}`
  105. }
  106. }
  107. /**
  108. * 将时间转换为UTC时间字符串,支持格式 yyyy-mm-dd hh:mm:ss
  109. * @description 按源格式返回
  110. * @param {string} timeStr 源时间
  111. * @param {string} type str 普通时间格式, utcStr yyyymmddThhmmssZ格式
  112. */
  113. function toISOStringByDate(timeStr, type = 'str') {
  114. const time = {}
  115. let newTime
  116. let date = new Date(timeStr.replace(/-/g, '/'))
  117. time.y = date.getUTCFullYear()
  118. time.m = addZero(date.getUTCMonth() + 1)
  119. time.d = addZero(date.getUTCDate())
  120. time.h = addZero(date.getUTCHours())
  121. time.min = addZero(date.getUTCMinutes())
  122. time.s = addZero(date.getUTCSeconds())
  123. if (type === 'utcStr') {
  124. newTime = `${time.y}${time.m}${time.d}T${time.h}${time.min}${time.s}Z`
  125. } else {
  126. newTime = `${time.y}-${time.m}-${time.d} ${time.h}:${time.min}:${time.s}`
  127. }
  128. return newTime
  129. }
  130. /**
  131. * 将时间转换为UTC时间字符串
  132. * @description 按源格式返回,目前支持格式1970-01-01 00:00:00
  133. * @param {string} timeStr 源时间
  134. * @param {string} type str 普通时间格式, utcStr yyyymmddThhmmssZ格式
  135. */
  136. function toISOString(timeStr, type) {
  137. try {
  138. if (REG.DATE.test(timeStr)) {
  139. // 格式 yyyy-mm-dd hh:mm:ss
  140. return toISOStringByDate(timeStr, type)
  141. } else if (REG.TIME.test(timeStr)) {
  142. // 格式 hh:mm:ss
  143. return toISOStringByTime(timeStr)
  144. }
  145. } catch (e) {
  146. return ''
  147. }
  148. throw new Error('Please enter date as yyyy-mm-dd hh:mm:ss')
  149. }
  150. /**
  151. * 将UTC时间转换为本地时间字符串,支持格式 hh:mm:ss
  152. * @description 默认传入的为UTC时间,此处由于各版本浏览器支持性不一,故使用Date.UTC()
  153. * @param {string} timeStr 源时间
  154. * @returns {object} 包含time和日期偏差
  155. */
  156. function toLocaleStringByTime(timeStr) {
  157. const time = {}
  158. let timeList = timeStr.split(':');
  159. let utcDate = Date.UTC(2000, 10, 24, timeList[0], timeList[1], timeList[2]);
  160. let date = new Date(utcDate);
  161. time.d = date.getDate()
  162. time.h = addZero(date.getHours())
  163. time.min = addZero(date.getMinutes())
  164. time.s = addZero(date.getSeconds())
  165. return {
  166. offset: time.d - 24,
  167. time: `${time.h}:${time.min}:${time.s}`
  168. }
  169. }
  170. /**
  171. * 将UTC时间转换为本地时间字符串,支持格式 yyyy-mm-dd hh:mm:ss
  172. * @description 默认传入的为UTC时间,此处由于各版本浏览器支持性不一,故使用Date.UTC()
  173. * @param {string} timeStr 源时间
  174. * @param {string} type str 普通时间格式, mmDDyy
  175. */
  176. function toLocaleStringByDate(timeStr, type = 'str') {
  177. const time = {}
  178. let newTime = timeStr.split(' ');
  179. let dateList = newTime[0].split('-');
  180. let timeList = newTime[1].split(':');
  181. let utcDate = Date.UTC(dateList[0], dateList[1] - 1, dateList[2], timeList[0], timeList[1], timeList[2]);
  182. let date = new Date(utcDate);
  183. time.y = date.getFullYear()
  184. time.m = addZero(date.getMonth() + 1)
  185. time.d = addZero(date.getDate())
  186. time.h = addZero(date.getHours())
  187. time.min = addZero(date.getMinutes())
  188. time.s = addZero(date.getSeconds())
  189. if (type === 'mmDDyy') {
  190. return `${time.m}-${time.d}-${time.y} ${time.h}:${time.min}:${time.s}`
  191. }
  192. return `${time.y}-${time.m}-${time.d} ${time.h}:${time.min}:${time.s}`
  193. }
  194. /**
  195. * 将UTC时间转换为本地时间字符串
  196. * @description 默认传入的为UTC时间,目前支持格式1970-01-01 00:00:00
  197. * @param {string} timeStr 源时间
  198. */
  199. function toLocaleString(timeStr) {
  200. if (!timeStr) {
  201. return
  202. }
  203. try {
  204. if (REG.DATE.test(timeStr)) {
  205. // 格式 yyyy-mm-dd hh:mm:ss
  206. return toLocaleStringByDate(timeStr)
  207. } else if (REG.TIME.test(timeStr)) {
  208. // 格式 hh:mm:ss
  209. return toLocaleStringByTime(timeStr)
  210. } else if (REG.DATE_Z.test(timeStr)) {
  211. // 格式 yyyymmddThhmmssZ
  212. let newTime = timeStr.replace(/[^0-9]/g, '')
  213. let date = `${newTime.slice(0, 4)}-${newTime.slice(4, 6)}-${newTime.slice(6, 8)}`
  214. let time = `${newTime.slice(8, 10)}:${newTime.slice(10, 12)}:${newTime.slice(12, 14)}`
  215. return toLocaleStringByDate(`${date} ${time}`)
  216. } else if (REG.DATE_M_D_Y.test(timeStr)) {
  217. let newTime = timeStr.split(' ');
  218. let dateList = newTime[0].split('-');
  219. let time = newTime[1];
  220. return toLocaleStringByDate(`${dateList[2]}-${dateList[0]}-${dateList[1]} ${time}`, 'mmDDyy')
  221. } else if (REG.DATE_Z_S.test(timeStr)) {
  222. // 格式 yyyymmddThhmmss.000Z 带毫秒的utc格式
  223. let newTime = timeStr.replace(/[^0-9]/g, '')
  224. let date = `${newTime.slice(0, 4)}-${newTime.slice(4, 6)}-${newTime.slice(6, 8)}`
  225. let time = `${newTime.slice(8, 10)}:${newTime.slice(10, 12)}:${newTime.slice(12, 14)}`
  226. return toLocaleStringByDate(`${date} ${time}`)
  227. }
  228. } catch (e) {
  229. console.log('Please enter date as yyyy-mm-dd hh:mm:ss')
  230. return ''
  231. }
  232. throw new Error('Please enter date as yyyy-mm-dd hh:mm:ss')
  233. }
  234. /**
  235. * 格式化时间
  236. *
  237. * @param {any} date
  238. * @param {any} format
  239. * @returns
  240. */
  241. function dateFormat(date, format) {
  242. let format1 = format;
  243. var o = {
  244. "M+": date.getMonth() + 1,
  245. "d+": date.getDate(),
  246. "H+": date.getHours(),
  247. "m+": date.getMinutes(),
  248. "s+": date.getSeconds(),
  249. "q+": Math.floor((date.getMonth() + 3) / 3),
  250. "S+": date.getMilliseconds()
  251. };
  252. if (!format1) {
  253. format1 = "yyyy-MM-dd";
  254. }
  255. if (/(y+)/.test(format1)) {
  256. format1 = format1.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  257. }
  258. if (/(S+)/.test(format1)) {
  259. format1 = format1.replace(RegExp.$1, (date.getMilliseconds() + "").substr(3 - RegExp.$1.length));
  260. }
  261. for (var k in o) {
  262. if (new RegExp("(" + k + ")").test(format1)) {
  263. format1 = format1.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  264. }
  265. }
  266. return format1;
  267. }
  268. /**
  269. * 获取当前UTC时间
  270. */
  271. function getCurrentUTCTime() {
  272. let retStr = '';
  273. let dateStr = dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss');
  274. if(dateStr){
  275. retStr = toISOString(dateStr, 'utcStr');
  276. }
  277. return retStr
  278. }
  279. /**
  280. * 获取当前时间
  281. */
  282. function getCurrentTime() {
  283. let retStr = '';
  284. let dateStr = dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss');
  285. return dateStr
  286. }
  287. /**
  288. * 获取UTC时间
  289. */
  290. function getUTCTimeByTime(time) {
  291. let retStr = '';
  292. let dateStr = dateFormat(new Date(time), 'yyyy-MM-dd HH:mm:ss');
  293. if(dateStr){
  294. retStr = toISOString(dateStr, 'utcStr');
  295. }
  296. return retStr
  297. }
  298. /**
  299. * 获取当前浏览器客户端的时区
  300. * @description +0800为东八区
  301. * @returns {string} such as +0000 +0545
  302. */
  303. function getTimezoon() {
  304. let timezoonOffset = new Date().getTimezoneOffset();
  305. const flag = timezoonOffset > 0 ? '-' : '+';
  306. timezoonOffset = Math.abs(timezoonOffset);
  307. const hours = Math.floor(timezoonOffset / 60);
  308. const minute = timezoonOffset % 60;
  309. return flag + addZero(hours) + addZero(minute);
  310. }
  311. /**
  312. * 格式化时间为对象形式
  313. *
  314. * @description
  315. * 接收Date、数字或字符串格式的UTC时间、UTC时间*1000(单位秒)
  316. * 转换为时间对象
  317. *
  318. * @method dateToObject
  319. * @param {Object | String | Number} param 时间
  320. * @returns {object} 日期结果对象
  321. */
  322. function dateToObject(param) {
  323. let date = null
  324. if (typeof param === 'object') {
  325. date = param;
  326. } else if (typeof param === 'string') {
  327. if (param.toString().length === 13) {
  328. date = new Date(param.replace(/-/g, '/'));
  329. } else if (param.toString().length === 10) {
  330. date = new Date(param * 1000);
  331. } else {
  332. date = new Date(param.replace(/-/g, '/'));
  333. }
  334. } else if (typeof param === 'number') {
  335. date = new Date(param);
  336. }
  337. if (!date) {
  338. return {};
  339. }
  340. const dateObj = {
  341. year: date.getFullYear(),
  342. month: addZero(date.getMonth() + 1),
  343. day: addZero(date.getDate()),
  344. hour: addZero(date.getHours()),
  345. minute: addZero(date.getMinutes()),
  346. second: addZero(date.getSeconds())
  347. }
  348. return dateObj
  349. }
  350. /**
  351. * 根据时间字符串获取年月日日期 20180530,2018年9月30日;
  352. * @param param
  353. */
  354. function getDateString(param,type=0){
  355. let date = new Date(param);
  356. let year = date.getFullYear()+"";
  357. let month=(date.getMonth()+1)+"";
  358. let day=date.getDate();
  359. let tmp="";
  360. month=month<10?"0"+month:month;
  361. day=day<10?"0"+day:day;
  362. if(type===0){
  363. tmp=year+month+day;
  364. }else if(type===1){
  365. tmp=year+"-"+month+"-"+day;
  366. }else{
  367. tmp=param;
  368. }
  369. return tmp;
  370. }
  371. /**
  372. * 根据时间字符串获取时分秒;
  373. * @param param
  374. */
  375. function getTimeString(param,type=0) {
  376. let date = new Date(param);
  377. let hour = date.getHours();
  378. let min = date.getMinutes();
  379. let sec = date.getSeconds();
  380. hour = hour < 10 ? "0" + hour : hour;
  381. min = min < 10 ? "0" + min : min;
  382. sec = sec < 10 ? "0" + sec : sec;
  383. let tmp = "";
  384. if (type === 0) {
  385. tmp = hour + ":" + min + ":" + sec;
  386. }
  387. return tmp;
  388. }
  389. /**
  390. * 获取系统的当前时间;
  391. * @param param
  392. */
  393. function getNowFormatData(type=0){
  394. let date = new Date();
  395. let year = date.getFullYear();
  396. let month=date.getMonth()+1;
  397. let day=date.getDate();
  398. let hour = date.getHours();
  399. let min = date.getMinutes();
  400. let sec = date.getSeconds();
  401. month=month<10?"0"+month:month;
  402. day=day<10?"0"+day:day;
  403. hour=hour<10?"0"+hour:hour;
  404. min=min<10?"0"+min:min;
  405. sec=sec<10?"0"+sec:sec;
  406. let tmp="";
  407. if(type===0){
  408. tmp=year+month+day+" "+hour+":"+min+":"+sec;
  409. }else if(type===1){
  410. tmp=year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec;
  411. }else{
  412. tmp=param;
  413. }
  414. return tmp;
  415. }
  416. /**
  417. * 格式化时间
  418. *
  419. * @param {any} date
  420. * @param {any} format
  421. * @returns
  422. */
  423. function dateFormat(date, format) {
  424. let format1 = format;
  425. var o = {
  426. "M+": date.getMonth() + 1,
  427. "d+": date.getDate(),
  428. "H+": date.getHours(),
  429. "m+": date.getMinutes(),
  430. "s+": date.getSeconds(),
  431. "q+": Math.floor((date.getMonth() + 3) / 3),
  432. "S+": date.getMilliseconds()
  433. };
  434. if (!format1) {
  435. format1 = "yyyy-MM-dd";
  436. }
  437. if (/(y+)/.test(format1)) {
  438. format1 = format1.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  439. }
  440. if (/(S+)/.test(format1)) {
  441. format1 = format1.replace(RegExp.$1, (date.getMilliseconds() + "").substr(3 - RegExp.$1.length));
  442. }
  443. for (var k in o) {
  444. if (new RegExp("(" + k + ")").test(format1)) {
  445. format1 = format1.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  446. }
  447. }
  448. return format1;
  449. }
  450. /**
  451. * valifyTime 校验时间格式
  452. * isTimeContainTime 判定两组时间序列是否存在重复(交叉或包含)
  453. * toISOString 将时间转换为UTC时间字符串
  454. * toLocaleString 将时间转换为本地时间字符串
  455. * getTimezoon 获取当前时区
  456. */