时间戳 日期 转换

需求:
时间段 格式 示例
当前日期 HH:MM 10:30
前一天 昨天HH:MM 昨天10:30
(前一天-本年1月1号] MM-DD HH:MM 11-02 10:30
(本年1月1号-更早) YYYY-MM-DD
HH:MM 2021-10-30 10:30

import moment from "moment";

const formatDate = (time: any) => {
  const operateTime = moment(time).format("YYYY-MM-DD HH:mm"); // 将时间戳转换为日期格式

  const operateYestTime = moment(time).format("YYYY-MM-DD");
  const yestday = moment().subtract(1, "days").format("YYYY-MM-DD"); // 昨天
  const padZero = (target: string | number) => `${target}`.padStart(2, "0");

  const date = new Date(operateTime.replace(/-/g, "/"));
  const today = new Date();
  const toYear = today.getFullYear();
  const toMon = padZero(today.getMonth() + 1);
  const toDays = padZero(today.getDate());
  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1);
  const days = padZero(date.getDate());
  const hour = padZero(date.getHours());
  const min = padZero(date.getMinutes());
  const dateInfo =
    (
      {
        [`${toMon == month && toDays == days}`]: `${month}-${days} `,
        [`${toYear == year}`]: `${year}-${month}-${days} `,
      } as Record<string, any>
    )?.["false"] ?? "";

  return operateYestTime === yestday
    ? `昨天 ${hour}:${min}`
    : `${dateInfo}${hour}:${min}`;
};

console.log(formatDate(1678243801000)); // 调用
日期转时间戳
const date = new Date('2023-03-10 10:50:01');
const time1 = date.getTime();
console.log(time1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值