moment 基本使用方法

moment 常用方法的值

  • new Date()

Mon Mar 30 2020 16:35:37 GMT+0800 (中國標準時間)

  • moment()
    在這裏插入圖片描述
  • moment(new Date())

在這裏插入圖片描述

  • moment(new Date()).unix()

1585560937

  • moment().format(‘YYYYMMDDHH’) – 當前日期,精確到小時

2020033017

  • moment(new Date()).format(‘YYYY-MM-DD HH:mm:ss’)

2020-03-30 16:35:37

  • moment().subtract(1, ‘day’).format(‘YYYYMMDD’) – 昨天

20200329

  • moment().subtract(1, ‘hour’).toDate() – 1小時前

Mon Mar 30 2020 16:35:37 GMT+0800 (中國標準時間)

  • moment().toDate() – 當前時間

Mon Mar 30 2020 15:35:37 GMT+0800 (中國標準時間)

import moment, { Moment } from 'moment';

export const DEFAULT_FORMAT = 'YYYY-MM-DD HH:mm';
const DEFAULT_HOUR_FORMAT = 'YYYYMMDDHH';
const DEFAULT_HISTORY_FORMAT = 'YYYYMMDD';
export const DEFAULT_DATE_FORMAT = 'yyyy-MM-dd HH:mm';

/* 獲得默認當前時間 */
export const getNowDateRange = (type: string = 'hour'): string[] => {
    let dateRange!: string[];
    switch (type) {
        case 'hour':
            dateRange = getHourRange();
            break;
        case 'day':
            dateRange = getDayRange();
            break;
        case 'week':
            dateRange = getWeekRange();
            break;
        case 'month':
            dateRange = getMonthRange();
            break;
    }
    return dateRange;
};

/* 獲取小時日期範圍 */
export const getHourRange = (date: string = moment().format(DEFAULT_HOUR_FORMAT)): string[] => {
    return [moment(date, DEFAULT_HOUR_FORMAT).startOf('hour').format(DEFAULT_FORMAT), moment(date, DEFAULT_HOUR_FORMAT).endOf('hour').format(DEFAULT_FORMAT)];
    // ["2020-03-30 17:00", "2020-03-30 17:59"]
};

/* 獲取日期範圍 */
export const getDayRange = (date: string = moment().subtract(1, 'day').format(DEFAULT_HISTORY_FORMAT)): string[] => {
    return [moment(date, DEFAULT_HISTORY_FORMAT).startOf('day').format(DEFAULT_FORMAT), moment(date, DEFAULT_HISTORY_FORMAT).endOf('day').format(DEFAULT_FORMAT)];
    // ["2020-03-29", "2020-03-30"]
};

/* 判斷是否是未來時間 */
export const isFuture = (date: string = '2020-03-30 17:00', type: string = 'hour'): boolean => {
    let d!: Moment;
    if (type === 'hour') {
        d = moment(date, DEFAULT_HOUR_FORMAT).startOf('hour');
    } else if (type === 'day') {
        d = moment(date).add(2, 'day');
    } else {
        d = moment(date);
    }
    return moment().isBefore(d);
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章