格式介紹
moment對(duì)象
使用 UI 框架的時(shí)間相關(guān)組件時(shí)(如 ant-design),默認(rèn)的綁定值的格式往往為這種。
/* 控制臺(tái)的打印效果 */
Moment {...}
Moment {
_d: (...)
_isAMomentObject: true
_isUTC: (...)
_isValid: (...)
_locale: (...)
_pf: (...)
}
字符串
部分栗子 | 對(duì)應(yīng) |
---|---|
YYYY-MM-DD HH:mm:ss | 2022-04-12 20:30:00 |
YYYY/MM/DD HH:mm:ss | 2022/04/12 20:30:00 |
YYYY/MM/DD hh:mm:ss | 2022/04/12 08:30:00 |
YYYY/M/D HH:mm:ss | 2022/4/12 20:30:00 |
YYYY/MM/DD HH:mm | 2022/04/12 20:30 |
日期對(duì)象
通過 new Date() 獲得。
Thu Apr 14 2022 20:40:11 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)
?? 兩個(gè)日期對(duì)象間可以比較大小
?? 全文本字符串格式
moment.js庫(kù)
moment自增一天
// 自增一天
moment().add(1,'days')
// 自減一天
moment().subtract(1, 'days')
// 年月時(shí)分秒,將第二個(gè)參數(shù)替換為以下字符串
years months hours minutes seconds
// 同時(shí)自增日和月
moment().add({ days:7, months:1 });
moment設(shè)置為頭尾
表達(dá)式 | 含義 |
---|---|
moment().startOf(‘year’) | 設(shè)置為今年的1月1日的00:00:00 |
moment().endOf(‘year’) | 設(shè)置為今年的12月31號(hào)的23:59:59 |
moment().startOf(‘day’); | 設(shè)置為今天的00:00:00 |
moment().endOf(‘day’); | 設(shè)置為今天的23:59:59 |
?? 類似的參數(shù)還有 month、quarter、week、hour、minute、second
moment轉(zhuǎn)換為字符串
import moment from 'moment';
methods: {
moment,
handleDemo(momentObj) {
/* moment 轉(zhuǎn)化為 字符串,如 '2021-12-30 20:00:00' */
const demo = moment(momentObj).format('YYYY-MM-DD HH:mm:ss')
},
}
自定義時(shí)分秒
startTime = `${moment(start).format('YYYY-MM-DD')} 00:00:00`;
endTime = `${moment(end).format('YYYY-MM-DD')} 23:59:59`;
字符串轉(zhuǎn)換為moment
import moment from 'moment';
methods: {
moment,
handleDemo() {
let demo = '2021-12-30 20:00:00'
/* 字符串 轉(zhuǎn)化為 moment */
const startTime = moment(demo, 'YYYY-MM-DD HH:mm:ss');
},
}
字符串轉(zhuǎn)換為字符串
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script>
var str = '2021/11/15 11:20:00';
var momentObj = moment(str, 'YYYY/MM/DD HH:mm:ss');
momentObj.format('YYYY-MM-DD'); // 2021-11-15
momentObj.format('HH:mm:ss'); // 11:20:00
</script>
?? HH
代表24小時(shí)制,hh
代表12小時(shí)制
獲取當(dāng)前時(shí)間的字符串
moment().format('YYYY-MM-DD'); // 示例:2022-01-01
moment().format('HH:mm:ss'); // 示例:00:00:00
獲取昨天的字符串
假設(shè)今天的日期為
2022-1-1
,將得到2021-12-31
const today = new Date();
today.setTime(today.getTime() - 24 * 60 * 60 * 1000); // 減上一天的日期對(duì)象
const yesterday = moment(today).format('YYYY-MM-DD');
日期轉(zhuǎn)換為moment
const today = new Date()
const momentObj = moment(new Date())
原生
新建日期對(duì)象
① new Date()
② new Date(year, month, day, hours, minutes, seconds, milliseconds)
③ new Date(milliseconds)
④ new Date(date string)
-
①:用當(dāng)前日期和時(shí)間創(chuàng)建新的日期對(duì)象
-
②:按順序分別指定年、月、日、小時(shí)、分鐘、秒和毫秒;至少要有年和月,否則會(huì)被視作毫秒
-
③:創(chuàng)建零時(shí)加毫秒的新日期對(duì)象
-
④:從日期字符串創(chuàng)建一個(gè)新的日期對(duì)象
new Date("October 13, 2014 11:13:00") new Date("2019-03-02 12:46:00") new Date("2019-3-2 12:46:00") // 在某些瀏覽器中,不帶前導(dǎo)零的月或其會(huì)產(chǎn)生錯(cuò)誤 new Date("2018-02-19") new Date("2018-02") new Date("2018")
?? 零時(shí)區(qū)為 1970 年 1 月 1 日 00:00:00 UTC
?? JavaScript 從 0 到 11 計(jì)算月份;需要注意月份的設(shè)置 和 getMonth 方法
新建日期對(duì)象-適配ios
從日期字符串創(chuàng)建一個(gè)新的日期對(duì)象時(shí),需要額外注意:
const str1 = '2022-2-12 12:00:00'
const str2 = '2022-02-12 12:00:00'
const str3 = '2022/02/12 12:00:00'
/* 結(jié)果相同 */
const result1 = new Date(str1.replace(/-/g, '/'))
const result2 = new Date(str2.replace(/-/g, '/'))
const result3 = new Date(str3.replace(/-/g, '/'))
?? ios 不能解析 YYYY-MM-DD 的格式,需要轉(zhuǎn)化為 YYYY/MM/DD
日期獲取方法
方法 | 描述 |
---|---|
getDate() | 獲取天(1-31) |
getDay() | 獲取一周的某一天的數(shù)字(0-6) |
getFullYear() | 獲取四位的年(yyyy) |
getHours() | 獲取小時(shí)(0-23) |
getMilliseconds() | 獲取毫秒(0-999) |
getMinutes() | 獲取分(0-59) |
getMonth() | 獲取月(0-11) |
getSeconds() | 獲取秒(0-59) |
getTime() | 獲取時(shí)間(從 1970 年 1 月 1 日至今) |
注意:對(duì)于 getDay() 的返回值,星期天為 0, 星期一為 1, 以此類推。
日期設(shè)置方法
方法 | 描述 |
---|---|
setDate() | 以數(shù)值(1-31)設(shè)置日 |
setFullYear() | 設(shè)置年(可選月和日) |
setHours() | 設(shè)置小時(shí)(0-23);必選時(shí),可選分、秒、毫秒;-1為昨天最后時(shí),24為明日首時(shí) |
setMilliseconds() | 設(shè)置毫秒(0-999) |
setMinutes() | 設(shè)置分(0-59) |
setMonth() | 設(shè)置月(0-11) |
setSeconds() | 設(shè)置秒(0-59) |
setTime() | 設(shè)置時(shí)間(從 1970 年 1 月 1 日至今的毫秒數(shù)) |
?? 對(duì)于 setHours,在 EMCAScript 標(biāo)準(zhǔn)化之前,不支持后面幾個(gè)參數(shù),也許也不支持-1等。
日期對(duì)象自增一天
const myDate = new Date()
console.log(myDate) // 此時(shí)的日期對(duì)象
myDate.setDate(myDate.getDate() + 1)
console.log(myDate) // 明天此時(shí)的日期對(duì)象
?? 涉及到跨月/跨年時(shí),也會(huì)自動(dòng)處理。
日期對(duì)象自增一時(shí)
const myDate = new Date()
console.log(myDate) // 此時(shí)的日期對(duì)象
myDate.setHours(myDate.getHours() + 1)
console.log(myDate) // 一小時(shí)后的日期對(duì)象
?? 涉及到跨月/跨年/跨日時(shí),也會(huì)自動(dòng)處理。
日期對(duì)象-獲取當(dāng)日零點(diǎn)
//獲取當(dāng)天零點(diǎn)的時(shí)間
const stamp1 = new Date(new Date().setHours(0, 0, 0, 0));
//獲取當(dāng)天23:59:59的時(shí)間
const stamp2 = new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1);
日期對(duì)象轉(zhuǎn)化為時(shí)間戳
毫秒
const timestamp = dateObj.getTime()
日期對(duì)象轉(zhuǎn)化為字符串
導(dǎo)出格式:
YYYY-MM-DD HH:mm:ss
// 日期對(duì)象轉(zhuǎn)化為 YYYY-MM-DD HH:mm:ss
dateToTime (date) {
const Y = date.getFullYear() + '-'
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
const m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return Y + M + D + h + m + s
},
// 日期對(duì)象轉(zhuǎn)化為 YYYY-MM-DD HH:mm
dateToTime1 (date) {
const Y = date.getFullYear() + '-'
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
return Y + M + D + h + m
},
// 日期對(duì)象轉(zhuǎn)化為 HH:mm
dateToTime2 (date) {
const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
return h + m
},
時(shí)間戳加一天
毫秒
const Next = timestamp + 24 * 60 * 60 * 1000
時(shí)間戳轉(zhuǎn)化為字符串
導(dǎo)出格式:
YYYY-MM-DD HH:mm:ss
// 時(shí)間戳轉(zhuǎn)化為 YYYY-MM-DD hh:mm:ss
timestampToTime (timestamp) {
const date = new Date(timestamp) // 時(shí)間戳為10位需*1000,時(shí)間戳為13位的話不需乘1000
const Y = date.getFullYear() + '-'
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
const m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return Y + M + D + h + m + s
},
導(dǎo)出格式:
YYYY-MM-D H:m:s
// 時(shí)間戳轉(zhuǎn)化為 YYYY-MM-DD hh:mm:ss
timestampToTime (timestamp) {
const date = new Date(timestamp) // 時(shí)間戳為10位需*1000,時(shí)間戳為13位的話不需乘1000
const Y = date.getFullYear() + '-'
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const D = date.getDate() + ' '
const h = date.getHours() + ':'
const m = date.getMinutes() + ':'
const s = date.getSeconds()
return Y + M + D + h + m + s
},
時(shí)間戳轉(zhuǎn)(天)時(shí)分秒
毫秒
-
默認(rèn)返回天數(shù),返回格式 ‘1天12:05:00’
-
默認(rèn)時(shí)長(zhǎng)小于一天時(shí),返回格式 ‘23:00:00’
-
會(huì)將天數(shù)、時(shí)、分、秒返回,可自由拼接
/**
* 將時(shí)長(zhǎng)轉(zhuǎn)成xx天HH:mm:ss格式
* @param { Number } time 時(shí)長(zhǎng),單位ms
* @param { Boolean } showDay 是否顯示【天】
* @return 返回時(shí)間,也可以根據(jù)自己需要組裝格式,例如{ time2: xxx }
*/
export function fomrtatCountDown(time, showDay = true) {
time = parseInt(time / 1000)
let oneMinute = 60
let oneHour = 60 * oneMinute
let oneDay = 24 * oneHour
let day = parseInt(time / oneDay)
if (showDay) {
day = day > 0 ? day : ''
time = time - day * oneDay
}
let hour = parseInt(time / oneHour)
hour = hour >= 10 ? hour : '0' + hour
time = time - hour * oneHour
let minute = parseInt(time / oneMinute)
minute = minute >= 10 ? minute : '0' + minute
let second = time - minute * oneMinute
second = second >= 10 ? second : '0' + second
return {
time: (showDay && day ? `${day}天` : '') + `${hour}:${minute}:${second}`,
day,
hour,
minute,
second
}
}
?? 如果不需要獲取到天,即允許小時(shí)數(shù)大于23,第二參傳false即可。
更多
日期對(duì)象差轉(zhuǎn)(天)時(shí)分秒
傳入今天和明天同一時(shí)間(默認(rèn)),返回 [1, 0, 0, 0]
傳入今天和明天同一時(shí)間(補(bǔ)位),返回 [‘01’, ‘00’, ‘00’, ‘00’]
/**
* 得到兩個(gè)時(shí)間相關(guān)的天數(shù)、小時(shí)、分鐘、秒
* @return {Array} 返回?cái)?shù)組固定4個(gè)
* @param {Object} startData
* @param {Object} endDate
* @param {Boolean} fixed_2 是否將每個(gè)單位補(bǔ)為2位
*/
const getDiffTimes = function(startData, endDate, fixed_2 = false) {
//相差的總秒數(shù)
let totalSeconds = parseInt((endDate - startData) / 1000)
// 取天數(shù)后取模(余數(shù))
let days = Math.floor(totalSeconds / (60 * 60 * 24))
let modulo = totalSeconds % (60 * 60 * 24)
// 取小時(shí)數(shù)后取模(余數(shù))
let hours = Math.floor(modulo / (60 * 60))
modulo = modulo % (60 * 60)
// 分鐘
let minutes = Math.floor(modulo / 60)
// 秒(通過取模獲取)
let seconds = modulo % 60
if (fixed_2) {
days = days < 10 ? '0' + days : days
hours = hours < 10 ? '0' + hours : hours
minutes = minutes < 10 ? '0' + minutes : minutes
seconds = seconds < 10 ? '0' + seconds : seconds
}
//輸出到頁(yè)面
//console.log(days + "天" + hours + ":" + minutes + ":" + seconds);
return [days, hours, minutes, seconds]
}
?? 如果不需要獲取兩個(gè)日期對(duì)象間的天數(shù),即允許小時(shí)數(shù)大于23,去除去天數(shù)及其后的取模即可。
補(bǔ)充的話
在倉(cāng)庫(kù),還提供了許多前端常見需求及實(shí)現(xiàn)的歸納整理,歡迎客官看看~文章來源:http://www.zghlxwxcb.cn/news/detail-703179.html
如果這篇筆記能夠幫助到你,請(qǐng)幫忙在 github 上點(diǎn)亮 star
,感謝!文章來源地址http://www.zghlxwxcb.cn/news/detail-703179.html
到了這里,關(guān)于前端常見需求整理 - 日期處理(包含moment、時(shí)間戳、日期對(duì)象)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!