moment 时间获取的方法

1.官网地址:http://momentjs.cn/icon-default.png?t=M666http://momentjs.cn/

2.安装

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

3.utils 方法

import moment from "moment";
// 年月日
export const shortTime = function (value) {
  return moment(value).format("YYYY-MM-DD");
};

// 年月日-时分秒
export const time = function (value) {
  return moment(value).format("YYYY-MM-DD HH:mm:ss");
};

// 年月
export const monthTime = function (value) {
  return moment(value).format("YYYY-MM");
};

// 年
export const yearTime = function (value) {
  return moment(value).format("YYYY");
};

// 月
export const getMonth = function (value) {
  return moment(value).format("MM");
};

// 时分秒
export const secondsTime = function (value) {
  return moment(value).format("HH:mm:ss");
};

//获取当前日期的周六
export const saturdayTime = function (value) {
  return moment(value).endOf("week").format("YYYY-MM-DD");
};

//获取当前日期的周日
export const sundayTime = function (value) {
  return moment(value).day(7).format("YYYY-MM-DD");
};

//计算日期之间的天数
export const DateDiff = function (sDate1, sDate2) {
  var aDate, oDate1, oDate2, iDays;
  aDate = sDate1.split("-");
  oDate1 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]); //转换为02-05-2018格式
  aDate = sDate2.split("-");
  oDate2 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]);
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) + 1; //把相差的毫秒数转换为天数
  return iDays;
};

/**  addDate: 获取几天之后的时间
 *  date:起始时间对象
 *  days: Number 当前时间'2019/12/24',传入6,则返回'2019/12/30'
 *  key => years: 'y'   quarters: 'Q'   months: 'M'   weeks: 'w'    days: 'd'  hours: 'h'
 *
 */
export const addDate = function (
  date,
  days,
  key = "d",
  forchart = "YYYY-MM-DD"
) {
  return moment(date).add(days, key).format(forchart);
};

/** 通过减去时间来改变原始的 moment */
export const subDate = function (
  date,
  days,
  key = "d",
  forchart = "YYYY-MM-DD"
) {
  return moment(date).subtract(days, key).format(forchart);
};

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值