草庐IT

JS 对时间日期的转换与操作

UserGuan 2024-01-03 原文

JS 时间格式转换

this.timeFormatConvert(new Date()) // 2022-11-26 21:37:29

/** 时间格式转换
 * @param e 要转换的日期(如:Sat Nov 26 2022 21:37:29 GMT+0800 (中国标准时间))
 * @returns {string} 转换结果(如:2022-11-26 21:37:29)
 */
timeFormatConvert(e) {
  const Y = e.getFullYear(); // 年
  const M = this.prefixZero(e.getMonth() + 1); // 月
  const D = this.prefixZero(e.getDate()); // 日
  const H = this.prefixZero(e.getHours()); // 时
  const Mi = this.prefixZero(e.getMinutes()); // 分
  const S = this.prefixZero(e.getSeconds()); // 秒
  return Y + "-" + M + "-" + D + " " + H + ":" + Mi + ":" + S;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取当前年月日时分秒

this.getCurrTime("noGap") // 20221129154229

this.getCurrTime() // 2022-11-29 15:44:20

/** 获取当前年月日时分秒
 * @param e 默认.年月日时分秒 date.年月日 dateTime.年月日时分 noGap.无分隔符的年月日时分秒
 * @returns {string}
 */
getCurrTime(e = "") {
  const curDate = new Date(),
    T = {
      Y: curDate.getFullYear().toString(), // 年
      M: this.prefixZero(curDate.getMonth() + 1), // 月
      D: this.prefixZero(curDate.getDate()), // 日
      H: this.prefixZero(curDate.getHours()), // 时
      Mi: this.prefixZero(curDate.getMinutes()), // 分
      S: this.prefixZero(curDate.getSeconds()), // 秒
    },
    tDate = T.Y + "-" + T.M + "-" + T.D; // 年月日
  let result = tDate + " " + T.H + ":" + T.Mi + ":" + T.S; // 年月日时分秒
  if (e === "date") result = tDate; // 年月日
  if (e === "dateTime") result = tDate + " " + T.H + ":" + T.Mi; // 年月日时分
  if (e === "noGap") result = T.Y + T.M + T.D + T.H + T.Mi + T.S; // 无分隔符
  return result;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取n天前或n天后的日期

当前日期:2022-11-27

7天后的日期:this.getAgoLaterDate(7) // 2022-12-04

7天前的日期:this.getAgoLaterDate(-7) // 2022-11-20

/** 获取n天前或n天后的日期(默认当天)
 * @param n 需要的天数(+n之后的日期,-n之前的日期)
 * @returns {string} 默认返回当前日期
 */
getAgoLaterDate(n = 0) {
  const curTime = new Date(),
    D1 = curTime.getDate(),
    date = new Date(curTime);
  date.setDate(D1 + n);
  const Y2 = date.getFullYear(),
    M2 = this.prefixZero(date.getMonth() + 1),
    D2 = this.prefixZero(date.getDate());
  return Y2 + "-" + M2 + "-" + D2;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的周一和周日

this.getSpecifyMonSun() // {mon: '2022-11-21', sun: '2022-11-27'}

this.getSpecifyMonSun("2022/11/17") // {mon: '2022-11-14', sun: '2022-11-20'}

/** 获取指定日期的周一和周日(默认当前日期)
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @returns {{mon: string, sun: string}} 默认返回当前日期的周一和周末日期
 */
getSpecifyMonSun(e = new Date()) {
  const that = this,
    now = new Date(e),
    nowTime = now.getTime(),
    day = now.getDay() || 7, // 周日时day修改为7,否则获取的是下周一到周日的日期
    oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数
    mondayTime = new Date(nowTime - (day - 1) * oneDayTime), //周一的日期
    sundayTime = new Date(nowTime + (7 - day) * oneDayTime); //周日的日期
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = that.prefixZero(d.getMonth() + 1), // 月
      D = that.prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  return { mon: dataFormat(mondayTime), sun: dataFormat(sundayTime) };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的周一至周日的所有日期

this.getSpecifyWeekAllTime() // ['2023-01-30', '2023-01-31', '2023-02-01', '2023-02-02', '2023-02-03', '2023-02-04', '2023-02-05']

this.getSpecifyWeekAllTime('2023-01-19') // ['2023-01-16', '2023-01-17', '2023-01-18', '2023-01-19', '2023-01-20', '2023-01-21', '2023-01-22']

/** 获取指定日期的周一至周日的所有日期
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @param t date.只返回月与日(默认返回年月日)
 * @returns {*[]} 默认返回当前日期的周一至周日的所有日期
 */
getSpecifyWeekAllTime(e = new Date(), t = '') {
  const timeStamp = new Date(e).getTime(),
    curDay = new Date(e).getDay(),
    dateList = [];
  for (let i = 0; i < 7; i++) {
    const das = new Date(timeStamp + 24 * 60 * 60 * 1000 * (i - ((curDay + 6) % 7)));
    const Y = das.getFullYear(), // 年
      M = this.prefixZero(das.getMonth() + 1), // 月
      D = this.prefixZero(das.getDate()); // 日
    let val = Y + '-' + M + '-' + D;
    if (t === 'date') val = M + '-' + D;
    dateList.push(val);
  }
  return dateList;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join('0') + num).slice(-n);
},

JS 获取指定日期的月初和月末

this.getSpecifyEarlyEndMonth() // {first: '2022-11-01', end: '2022-11-30'}

this.getSpecifyEarlyEndMonth("2022/09") // {first: '2022-09-01', end: '2022-09-30'}

/** 获取指定日期的月初和月末(默认当前月)
 * @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)
 * @returns {{end: string, first: string}} 默认返回当前月的月初和月末日期
 */
getSpecifyEarlyEndMonth(e = new Date()) {
  const that = this,
    nowDate = new Date(e), // 当前日期
    year = nowDate.getFullYear(), // 指定年
    month = nowDate.getMonth() + 1, // 指定月
    oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数
    firstDay = new Date(year, month - 1), // 当月第一天的日期
    lastDay = new Date(new Date(year, month).valueOf() - oneDayTime); // 当月最后一天的日期
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = that.prefixZero(d.getMonth() + 1), // 月
      D = that.prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  return { first: dataFormat(firstDay), end: dataFormat(lastDay) };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定年份季度的开始和结束日期

this.getSpecifyQuarter(); // { "first": "2023-01-01", "end": "2023-03-31" }

/** 获取指定年份季度的开始和结束日期(默认今年的第一季度)
 * @param year 指定的年份
 * @param qtr 指定的季度
 * @returns {{end: string, first: string}} 默认返回今年第一季度的日期
 */
getSpecifyQuarter(year = new Date().getFullYear(), qtr = 1) {
  let val = 0; // 第一季度
  if (qtr === 2) {
    val = 3; // 第二季度
  } else if (qtr === 3) {
    val = 6; // 第三季度
  } else if (qtr === 4) {
    val = 9; // 第四季度
  }
  const startDate = new Date(year, val, 1);
  const endDate = new Date(year, val + 2, getMonthDays(year, val + 2));
  // 日期格式化
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = prefixZero(d.getMonth() + 1), // 月
      D = prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  // 数字位数不够,数字前面补零
  function prefixZero(num = 0, n = 2) {
    return (Array(n).join("0") + num).slice(-n);
  }
  // 获得指定月份的天数
  function getMonthDays(y, m) {
    const monthStart = new Date(y, m, 1);
    const monthEnd = new Date(y, m + 1, 1);
    return (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
  }
  return { first: dataFormat(startDate), end: dataFormat(endDate) };
},

JS 根据当前时间判断是早上、中午、下午

this.getCurTimeState() // 晚上好

/** 根据当前时间判断是早上、中午、下午
 * @returns {string} 返回当前时间段对应的状态
 */
getCurTimeState() {
  const nowTime = new Date(), // 获取当前时间
    hour = nowTime.getHours(); // 获取当前小时
  let result = ""; // 设置默认文字
  // 判断当前时间段
  if (hour >= 0 && hour <= 10) {
    result = "早上好";
  } else if (hour > 10 && hour <= 14) {
    result = "中午好";
  } else if (hour > 14 && hour <= 18) {
    result = "下午好";
  } else if (hour > 18 && hour <= 24) {
    result = "晚上好";
  }
  return result; // 返回当前时间段对应的状态
},

JS 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等

this.timeConvertReveal("2020-11-27 14:38:16") // 2年前

this.timeConvertReveal() // 刚刚

/** 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等(默认刚刚)
 * @param e 需要转换的时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss)
 * @returns {string} 默认返回刚刚
 */
timeConvertReveal(e = new Date()) {
  const minute = 1000 * 60, // 分钟
    hour = minute * 60, // 小时
    day = hour * 24, // 天
    week = day * 7, // 周
    month = day * 30, // 月
    year = month * 12, // 年
    curTime = new Date().getTime(), // 当前时间的时间戳
    specifyTime = new Date(e), // 指定时间的时间戳
    mistiming = curTime - specifyTime, // 时间差
    yearDiffer = mistiming / year, // 年差
    monthDiffer = mistiming / month, // 月差
    weekDiffer = mistiming / week, // 周差
    dayDiffer = mistiming / day, // 天差
    hourDiffer = mistiming / hour, // 时差
    minuteDiffer = mistiming / minute; // 分钟差
  let result = "-";
  if (yearDiffer >= 1) result = toInt(yearDiffer) + "年前";
  else if (monthDiffer >= 1) result = toInt(monthDiffer) + "月前";
  else if (weekDiffer >= 1) result = toInt(weekDiffer) + "周前";
  else if (dayDiffer >= 1) result = toInt(dayDiffer) + "天前";
  else if (hourDiffer >= 1) result = toInt(hourDiffer) + "小时前";
  else if (minuteDiffer >= 1) result = toInt(minuteDiffer) + "分钟前";
  else result = "刚刚";
  function toInt(num) {
    return parseInt(num.toString());
  }
  return result;
},

JS 获得指定月份的天数

this.getMonthDays("2022-10") // 31

/** 获得指定月份的天数(默认当前月)
 * @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)
 * @returns {number} 默认返回当前月的天数
 */
getMonthDays(e = new Date()) {
  const now = new Date(e), // 指定日期
    nowYear = now.getYear(), // 指定年份
    nowMonth = now.getMonth(), // 指定月份
    startDate = new Date(nowYear, nowMonth, 1), // 开始日期
    endDate = new Date(nowYear, nowMonth + 1, 1); // 结束日期
  return (endDate - startDate) / (1000 * 60 * 60 * 24);
},

JS 获取指定日期是周几

this.getCurrWeek("2022-11-24") // 周四

this.getCurrWeek() // 周二

/** 获取指定日期是周几
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @returns {string} 默认返回当前日期是周几
 */
getCurrWeek(e = new Date()) {
  const day = new Date(e).getDay(),
    weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return weeks[day];
},

JS 计算两个时间的时间差

this.getTimeDiff("2022-11-28 19:30:24") // {text: '时间已超过30分钟', timeDiff: '0天21时28分40秒40毫秒', dateObj: {day: 0, hour: 21, min: 28, sec: 40, ms: 40}}

/** 计算两个时间的时间差(timeDiff返回格式为xx天xx时xx分xx秒xx毫秒)
 * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [需小于结束时间])
 * @param endTime 结束时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前时间])
 * @returns {string|{timeDiff: string, text: string, dateObj: {sec: number, min: number, hour: number, ms: number, day: number}}}
 */
getTimeDiff(startTime, endTime = new Date()) {
  if (!startTime) return "错误:开始时间为必填";
  const diffVal = new Date(endTime) - new Date(startTime); // 两个时间戳相差的毫秒数
  if (diffVal < 0) return "错误:开始时间大于结束时间";
  const day = Math.floor(diffVal / (24 * 3600 * 1000)), // 计算相差的天数
    remainDay = diffVal % (24 * 3600 * 1000), // 计算天数后剩余的毫秒数
    hour = Math.floor(remainDay / (3600 * 1000)), // 计算相差的小时数
    remainHour = remainDay % (3600 * 1000), // 计算小时数后剩余的毫秒数
    min = Math.floor(remainHour / (60 * 1000)), // 计算相差的分钟数
    remainMinute = remainHour % (60 * 1000), // 计算分钟数后剩余的毫秒数
    sec = Math.round(remainMinute / 1000), // 计算相差的秒数
    remainSeconds = remainMinute % (60 * 1000), // 计算秒数后剩余的毫秒数
    ms = Math.round(remainSeconds / 1000), // 计算相差的毫秒数
    time = day + "天" + hour + "时" + min + "分" + sec + "秒" + ms + "毫秒",
    obj = { day: day, hour: hour, min: min, sec: sec, ms: ms };
  let val = "时间未超过30分钟";
  if (min > 30 || hour > 1) val = "时间已超过30分钟";
  return { text: val, timeDiff: time, dateObj: obj };
},

JS 从日期字符串中截取出年、月、日、时、分、秒

this.captureTime() // {day: "29", hour: "17", minute: "40", month: "11", second: "06", year: "2022"}

this.captureTime("2020-12-11 14:54:48") // {day: "11", hour: "14", minute: "54", month: "12", second: "48", year: "2020"}

/** 从日期字符串中截取出年、月、日、时、分、秒
 * @param e 需要截取的日期(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前日期])
 * @returns {{month: *, hour: *, year: *, day: *, minute: *, second: *}} 默认返回当前日期
 */
captureTime(e = null) {
  let time = e;
  if (!e) {
    const curDate = new Date(),
      T = {
        Y: curDate.getFullYear().toString(), // 年
        M: this.prefixZero(curDate.getMonth() + 1), // 月
        D: this.prefixZero(curDate.getDate()), // 日
        H: this.prefixZero(curDate.getHours()), // 时
        Mi: this.prefixZero(curDate.getMinutes()), // 分
        S: this.prefixZero(curDate.getSeconds()), // 秒
      };
    time = T.Y + "-" + T.M + "-" + T.D + " " + T.H + ":" + T.Mi + ":" + T.S;
  }
  const timeArr = time.replace(/[:. /]/g, "-").split("-"); // 将":. /"换为"-",再根据"-"分组
  return {
    year: timeArr[0], // 年
    month: timeArr[1], // 月
    day: timeArr[2], // 日
    hour: timeArr[3], // 时
    minute: timeArr[4], // 分
    second: timeArr[5], // 秒
  };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

有关JS 对时间日期的转换与操作的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  6. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  7. ruby - 检查日期是否在过去 7 天内 - 2

    我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/

  8. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

  9. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  10. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

随机推荐