Skip to content

日期

formatDate

格式化日期

typescript
type FormatType = 'yyyy' | 'yyyy-MM' | 'yyyy-MM-dd' | 'yyyy-MM-dd HH:mm' | 'yyyy-MM-dd HH:mm:ss';

/**
 * 格式化时间
 * 调用formatDate(strDate, 'yyyy-MM-dd');
 * @param strDate(中国标准时间、时间戳、Date对象等)
 * @param strFormat(返回格式)
 */
export function formatDate(strDate: string | number | Date, strFormat?: FormatType) {
  if (!strDate) {
    return;
  }
  if (!strFormat) {
    strFormat = 'yyyy-MM-dd';
  }
  switch (typeof strDate) {
    case 'string':
      strDate = new Date(strDate.replace(/-/, '/'));
      break;
    case 'number':
      strDate = new Date(strDate);
      break;
  }
  if (strDate instanceof Date) {
    const dict: any = {
      yyyy: strDate.getFullYear(),
      M: strDate.getMonth() + 1,
      d: strDate.getDate(),
      H: strDate.getHours(),
      m: strDate.getMinutes(),
      s: strDate.getSeconds(),
      MM: ('' + (strDate.getMonth() + 101)).substr(1),
      dd: ('' + (strDate.getDate() + 100)).substr(1),
      HH: ('' + (strDate.getHours() + 100)).substr(1),
      mm: ('' + (strDate.getMinutes() + 100)).substr(1),
      ss: ('' + (strDate.getSeconds() + 100)).substr(1),
    };
    return strFormat.replace(/(yyyy|MM?|dd?|HH?|mm?|ss?)/g, function () {
      return dict[arguments[0]];
    });

formatDate(new Date(), 'yyyy-MM-dd');

isAfterDate

检查是否在某日期后

typescript
/**
 * 检查是否在某日期后
 * @param dateA
 * @param dateB
 * @returns
 */
export const isAfterDate = (dateA: Date, dateB: Date) => dateA > dateB

isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)) // true

isBeforeDate

检查是否在某日期前

typescript
/**
 * 检查是否在某日期前
 * @param dateA
 * @param dateB
 * @returns
 */
export const isBeforeDate = (dateA: Date, dateB: Date) => dateA < dateB

isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)) // true

Released under the MIT License.