常用的日期格式获取、转换

获取本周、本月、本年的起止时间范围

  1. import dayjs from 'dayjs'
  2. import type { Dayjs } from 'dayjs'
  3. type TimeFlag = 'ymd' | 'ym' | 'ymdt'
  4. export type RangeValue = [Dayjs, Dayjs]
  5. export type RangeStamp = [number, number]
  6. export function formatTime(time: string | number, flag: TimeFlag): string {
  7. const timeObj = {
  8. ymd: 'YYYY-MM-DD',
  9. ym: 'YYYY-MM',
  10. ymdt: 'YYYY-MM-DD HH:mm:ss'
  11. }
  12. const date = dayjs(+time).format(timeObj[flag])
  13. console.log('🚀 ~ file: dateUtil.ts ~ line 13 ~ date', date)
  14. return date
  15. }
  16. export function getTheWeek(): RangeStamp {
  17. // 当天 0 点的时间戳
  18. const dateStamp = new Date(new Date().toLocaleDateString()).getTime()
  19. const weekStart = new Date(
  20. dateStamp - 3600 * 1000 * 24 * (new Date().getDay() - 1)
  21. )
  22. const weekEnd = new Date(
  23. dateStamp + 3600 * 1000 * 24 * (7 + 1 - new Date().getDay())
  24. )
  25. console.log(
  26. '🚀 ~ file: dateUtil.ts ~ line 46 ~ getTheWeek ~ weekStart',
  27. weekStart,
  28. weekStart.getTime()
  29. )
  30. console.log(
  31. '🚀 ~ file: dateUtil.ts ~ line 53 ~ getTheWeek ~ weekEnd',
  32. weekEnd,
  33. weekEnd.getTime()
  34. )
  35. const start_time = dayjs().startOf('week').format('YYYY-MM-DD HH:mm:ss')
  36. const end_time = dayjs().endOf('week').format('YYYY-MM-DD HH:mm:ss')
  37. console.log(
  38. '🚀 ~ file: dateUtil.ts ~ line 40 ~ getTheWeek ~ start_time',
  39. start_time,
  40. dayjs(start_time).valueOf()
  41. )
  42. console.log(
  43. '🚀 ~ file: dateUtil.ts ~ line 42 ~ getTheWeek ~ end_time',
  44. end_time,
  45. dayjs(end_time).valueOf()
  46. )
  47. const startStamp = dayjs(start_time).valueOf()
  48. const endStamp = dayjs(end_time).valueOf()
  49. return [startStamp, endStamp]
  50. }
  51. export function getTheMonth(): RangeStamp {
  52. const date = new Date()
  53. const monthStart = new Date(date.getFullYear(), date.getMonth(), 1) // 本月第一天
  54. const monthEnd = new Date(date.getFullYear(), date.getMonth() + 1, 1) // 本月的最后一天(取下月1号0点)
  55. console.log(
  56. '🚀 ~ file: dateUtil.ts ~ line 61 ~ getTheMonth ~ monthStart',
  57. monthStart,
  58. monthStart.getTime()
  59. )
  60. console.log(
  61. '🚀 ~ file: dateUtil.ts ~ line 71 ~ getTheMonth ~ monthEnd',
  62. monthEnd,
  63. monthEnd.getTime()
  64. )
  65. const start_time = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
  66. const end_time = dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss')
  67. console.log(
  68. '🚀 ~ file: dateUtil.ts ~ line 69 ~ getTheMonth ~ start_time',
  69. start_time,
  70. dayjs(start_time).valueOf()
  71. )
  72. console.log(
  73. '🚀 ~ file: dateUtil.ts ~ line 71 ~ getTheMonth ~ end_time',
  74. end_time,
  75. dayjs(end_time).valueOf()
  76. )
  77. const startStamp = dayjs(start_time).valueOf()
  78. const endStamp = dayjs(end_time).valueOf()
  79. return [startStamp, endStamp]
  80. }
  81. export function getTheYear(): RangeStamp {
  82. const date = new Date()
  83. const startTime = new Date(date.getFullYear(), 0, 1) // 本月第一天
  84. const endTime = new Date(date.getFullYear() + 1, 0, 1) // 本月的最后一天(取下月1号0点)
  85. console.log(
  86. '🚀 ~ file: dateUtil.ts ~ line 81 ~ getTheYear ~ start_time',
  87. startTime,
  88. startTime.getTime()
  89. )
  90. console.log(
  91. '🚀 ~ file: dateUtil.ts ~ line 91 ~ getTheYear ~ end_time',
  92. endTime,
  93. endTime.getTime()
  94. )
  95. const start_time = dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss')
  96. const end_time = dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')
  97. console.log(
  98. '🚀 ~ file: dateUtil.ts ~ line 99 ~ getTheYear ~ start_time',
  99. start_time,
  100. dayjs(start_time).valueOf()
  101. )
  102. console.log(
  103. '🚀 ~ file: dateUtil.ts ~ line 107 ~ getTheYear ~ end_time',
  104. end_time,
  105. dayjs(end_time).valueOf()
  106. )
  107. const startStamp = dayjs(start_time).valueOf()
  108. const endStamp = dayjs(end_time).valueOf()
  109. return [startStamp, endStamp]
  110. }

时间戳转换成格式化日期

  1. /*
  2. * @Author: hhn
  3. * @Date: 2020-07-05 16:57:46
  4. * @lastEditTime: Do not edit
  5. * @Description: timestamp缺省表示使用当前时间戳,formats默认格式是Y-m-d,例如2018-01-01。
  6. * @FilePath: \codehub\study\studying\javascript\test.js
  7. */
  8. var dateFormat = function(timestamp, formats) {
  9. // formats格式包括
  10. // 1. Y-m-d
  11. // 2. Y-m-d H:i:s
  12. // 3. Y年m月d日
  13. // 4. Y年m月d日 H时i分
  14. formats = formats || 'Y-m-d';
  15. var zero = function(value) {
  16. if (value < 10) {
  17. return '0' + value;
  18. }
  19. return value;
  20. };
  21. var myDate = timestamp ? new Date(timestamp) : new Date();
  22. var year = myDate.getFullYear();
  23. var month = zero(myDate.getMonth() + 1);
  24. var day = zero(myDate.getDate());
  25. var hour = zero(myDate.getHours());
  26. var minite = zero(myDate.getMinutes());
  27. var second = zero(myDate.getSeconds());
  28. return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
  29. return ({
  30. Y: year,
  31. m: month,
  32. d: day,
  33. H: hour,
  34. i: minite,
  35. s: second
  36. })[matches];
  37. });
  38. };
  39. let date = new Date()
  40. console.log("date", date)
  41. console.log("dateFormat(date)", dateFormat(date))

image.png

时间戳转化为显示为多少分钟前,多少天前的处理

  1. /*
  2. ** 时间戳显示为多少分钟前,多少天前的处理
  3. ** eg.
  4. ** console.log(dateDiff(1411111111111)); // 2014年09月19日
  5. ** console.log(dateDiff(1481111111111)); // 9月前
  6. ** console.log(dateDiff(1499911111111)); // 2月前
  7. ** console.log(dateDiff(1503211111111)); // 3周前
  8. ** console.log(dateDiff(1505283100802)); // 1分钟前
  9. */
  10. var dateDiff = function(timestamp) {
  11. // 补全为13位
  12. var arrTimestamp = (timestamp + '').split('');
  13. for (var start = 0; start < 13; start++) {
  14. if (!arrTimestamp[start]) {
  15. arrTimestamp[start] = '0';
  16. }
  17. }
  18. timestamp = arrTimestamp.join('') * 1;
  19. var minute = 1000 * 60;
  20. var hour = minute * 60;
  21. var day = hour * 24;
  22. var halfamonth = day * 15;
  23. var month = day * 30;
  24. var now = new Date().getTime();
  25. var diffValue = now - timestamp;
  26. // 如果本地时间反而小于变量时间
  27. if (diffValue < 0) {
  28. return '不久前';
  29. }
  30. // 计算差异时间的量级
  31. var monthC = diffValue / month;
  32. var weekC = diffValue / (7 * day);
  33. var dayC = diffValue / day;
  34. var hourC = diffValue / hour;
  35. var minC = diffValue / minute;
  36. // 数值补0方法
  37. var zero = function(value) {
  38. if (value < 10) {
  39. return '0' + value;
  40. }
  41. return value;
  42. };
  43. // 使用
  44. if (monthC > 12) {
  45. // 超过1年,直接显示年月日
  46. return (function() {
  47. var date = new Date(timestamp);
  48. return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
  49. })();
  50. } else if (monthC >= 1) {
  51. return parseInt(monthC) + "月前";
  52. } else if (weekC >= 1) {
  53. return parseInt(weekC) + "周前";
  54. } else if (dayC >= 1) {
  55. return parseInt(dayC) + "天前";
  56. } else if (hourC >= 1) {
  57. return parseInt(hourC) + "小时前";
  58. } else if (minC >= 1) {
  59. return parseInt(minC) + "分钟前";
  60. }
  61. return '刚刚';
  62. };
  63. console.log("dateDiff()", dateDiff())

image.png

微信小程序版

  1. const formatMsgTime = function (dateStr) {
  2. var dateObj = dateStr.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/')
  3. var targetDate = new Date(dateObj);
  4. var year = targetDate.getFullYear();
  5. var month = targetDate.getMonth() + 1;
  6. var day = targetDate.getDate();
  7. var hour = targetDate.getHours();
  8. var minute = targetDate.getMinutes();
  9. var second = targetDate.getSeconds();
  10. var nowDate = new Date();
  11. var now_new = Date.parse(nowDate.toString());
  12. var milliseconds = 0;
  13. var timeSpanStr;
  14. milliseconds = now_new - targetDate;
  15. if (milliseconds <= 1000 * 60 * 1) {
  16. timeSpanStr = '刚刚';
  17. }
  18. else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
  19. timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
  20. }
  21. else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
  22. timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
  23. }
  24. else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
  25. timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
  26. }
  27. else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == nowDate.getFullYear()) {
  28. timeSpanStr = month + '-' + day;
  29. } else {
  30. timeSpanStr = year + '-' + month + '-' + day;
  31. }
  32. return timeSpanStr;
  33. }
  34. module.exports = {
  35. formatMsgTime: formatMsgTime
  36. }

使用方法

1,将上述代码保存为utils-days.js文件,放置在小程序公用目录里;
2,在需要使用的页面或者模块的js文件头部,导入该文件;
3,const utilsDays = require(‘../utils/utils-days’);
4, 使用该方法;

示例代码

  1. this.setData({
  2. newDate: utilsDays.formatMsgTime(systemDate);
  3. })

获取当前日期的星期数 本年度第几周

  1. function getWeekNumber(date) {
  2. // date 'yyyy-MM-dd'
  3. date = new Date(date);
  4. var date2 = new Date(date.getFullYear(), 0, 1);
  5. var day1 = date.getDay();
  6. if (day1 == 0) day1 = 7;
  7. var day2 = date2.getDay();
  8. if (day2 == 0) day2 = 7;
  9. let d = Math.round((date.getTime() - date2.getTime() + (day2 - day1) * (24 * 60 * 60 * 1000)) / 86400000);
  10. var getFullYear = date.getFullYear();
  11. var getWeekNo = (Math.ceil(d / 7) + 1);
  12. getWeekNo = (getWeekNo > 9 ? "" : "0") + getWeekNo;
  13. //当周数大于52
  14. if ((Math.ceil(d / 7) + 1) > 52) {
  15. if (date.getMonth() == 11) {
  16. // 还在当年12月份,则为当年第53周
  17. return [getFullYear, "53"]
  18. }
  19. // 已经跨年,为下一年的第一周
  20. return [getFullYear + 1, "01"]
  21. }
  22. return [getFullYear, getWeekNo];
  23. }

JS 获取某月的天数

一三五七八十腊,31天永不差,四六九十一,每月30天,惟有二月二十八,闰年要把日加一。

这里面还有个闰年的计算规则:四年一闰,百年不闰,四百年再闰。可以被4整除,但是不能被100整除,除非可以被400整除。

  1. function getMonthCountDay(year, month){
  2. // year 为年份,month 为月份
  3. }
  4. [[2000,2],[2000,1],[2000,3],[2000,4],[2100,2],[2100,1],[2100,3],[2100,4],[2104,2],[2104,1],[2104,3],[2104,4],[2105,2],[2105,1],[2105,3],[2105,4],].map(v=>`${v} => ${getMonthCountDay.apply(null,v)}天`)

switch方案

  1. function getMonthCountDay (year, month) {
  2. switch (month){
  3. case 1:
  4. case 3:
  5. case 5:
  6. case 7:
  7. case 8:
  8. case 10:
  9. case 12:
  10. return 31
  11. case 4:
  12. case 6:
  13. case 9:
  14. case 11:
  15. return 30
  16. case 2:
  17. return year%400==0?(29):(year%4!=0||year%100==0?28:29)
  18. }
  19. }

Date API 处理日期溢出特性(进位)

  1. function getMonthCountDay (year, month) {
  2. return 32 - new Date(year, month-1, 32).getDate()
  3. }

Date API 处理日期溢出特性(退位方案)

  1. function getMonthCountDay (year, month) {
  2. return new Date(year, month, 0).getDate()
  3. }

image.png

https://juejin.cn/post/6942640606732615694#heading-6