1,
/** 时间戳转化为 YYYY-MM-DD */
export const timestampToTime = function (time: any) {
const date = new Date(time)
const y = date.getFullYear()
let m: any = date.getMonth() + 1
m = m < 10 ? '0' + m : m
let d: any = date.getDate()
d = d < 10 ? '0' + d : d
return y + '-' + m + '-' + d
}
2,
/**
* 日期转化 YYYY-MM-DD => YYYY年MM月DD日
* @param date string 日期
*/
export const changeDate = function (date: string) {
const [year, month, day] = date.split('-')
return `${year}年${month}月${day}日`
}
3,
/**
* 日期补零 YYYY-M-D => YYYY-0M-0D
* 日期补零 YYYY-M => YYYY-0M
* @param date string 日期
*/
export const dateFormatter = function (date: string) {
const year = date.split('-')[0]
let month = date.split('-')[1].split('-')[0]
let day = ''
month = Number(month) < 10 ? `0${month}` : month
if (date.split('-').length === 3) {
day = date.split('-')[2]
day = Number(day) < 10 ? `0${day}` : day
}
return date.split('-').length === 3 ? `${year}-${month}-${day}` : `${year}-${month}`
}
4,
/**
* 月转化: 25个月 => 2年1月
* eg1:剩余时间为321天,则显示为:剩余1年
* eg2:剩余时间为21天,则显示为:剩余1月
* eg3:剩余时间为381天,则显示为:剩余1年1月
*/
export const monthsFormatter = function (months: any) {
months = months === 12 ? '1年' : months % 12 === 0 ? `${months / 12}年` : `${Math.trunc(months / 12)}年${months % 12}月`
return months
}
放到utils中需要的页面内引入import { monthsFormatter } from ‘…/…/utils/common/time’
以上是整理的一些时间转换的方法!