首页 前端知识 JavaScript 常用方法(1):JS日期格式化函数、JS实现并列排序、JS实现数字每三位添加逗号、JS 实现根据日期和时间进行排序

JavaScript 常用方法(1):JS日期格式化函数、JS实现并列排序、JS实现数字每三位添加逗号、JS 实现根据日期和时间进行排序

2024-06-22 10:06:02 前端知识 前端哥 580 898 我要收藏

1、JS日期格式化函数

JS日期格式化转换方法

/**
 * @description 格式化时间
 * @param fmt 格式  如:yyyy-MM-dd、yyyy-MM-dd HH:mm:ss、yyyy年MM月dd日 W HH:mm:ss等
 * @param {String} date 时间戳
 * @returns {string|null}
 * 对 Date 的扩展,将 Date 转化为指定格式的 String , 年(y)、月(M)、日(d)、24小时(H)、分(m)、秒(s)、周(W)、季度(q)、毫秒(S)。
 * 年(y) 可以用1-4个占位符,月(M)、日(d)、24小时(H)、分(m)、秒(s)、季度(q)可以用 1-2 个占位符,周(W)、毫秒(S)(是 1-3 位的数字) 只能用一个占位符。
 * 
 * new Date() ==> Tue Apr 11 2023 09:43:51 GMT+0800 (中国标准时间)
 * dateFtt('yyyy-MM-dd', new Date()) ==> '2023-04-11'
 * dateFtt('yyyy-M-d', new Date()) ==> '2023-4-11'
 * dateFtt('yyyy-MM-dd HH:mm:ss', new Date()) ==> '2023-04-11 09:46:22'
 * dateFtt('yyyy-MM-dd W HH:mm:ss', new Date()) ==> '2023-04-11 星期二 09:48:33'
 * dateFtt('yyyy年MM月dd日 W HH:mm:ss', new Date()) ==> '2023年04月11日 星期二 09:49:51'
 * dateFtt('yyyy/MM/dd W HH:mm:ss', new Date()) ==> '2023/04/11 星期二 09:54:04'
 * dateFtt('yyyy-MM-dd W HH:mm:ss.S', new Date()) ==> '2023-04-11 星期二 10:03:38.543'
 */
export function dateFtt(fmt, date) {
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
    'W': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()], //星期
    // 有其他格式化字符需求可以继续添加,必须转化成字符串
  }
  // 处理年份 正则 y+ 匹配一个或多个y
  if (/(y+)/.test(fmt)) { 
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) 
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) { 
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) 
    }
  }
  return fmt
}

示例:

let str = '2023-04-06t15:00:00.000+08:00';
let dateee = new Date(str).toJSON();
let date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
// 或者 二者等效
let date = dateFtt("yyyy-MM-dd HH:mm:ss", new Date(new Date(str).getTime()));

2、JS 实现并列排序

参考:js排名[【分数相同,排名并列,按人数排名】

并列排名算法

使用:
在这里插入图片描述

    parallelSorting(list, value) {
      //并列排序
      for (let i = 0; i < list.length; i++) {
        if (i == 0) {
          list[i].index = i;
        } else {
          if (list[i - 1][value] == list[i][value]) {
            list[i].index = list[i - 1].index;
          } else {
            list[i].index = i;
          }
        }
      }
    },

代码优化后:

/**
 *  @description 实现数组并列排序
 * @param {Object[]} list - 需要排序的数组
 * @param {string} value - 需要排序的字段
 * @param {boolean} bol - true: 升序;false: 降序;默认为true 升序
 */
function parallelSorting(list, value, bol = true) {
  list.sort(function (a, b) {
    if (bol) {
      return a[value] - b[value];  // 升序
    } else {
      return b[value] - a[value];  // 降序
    }
  });
  for (let i = 0; i < list.length; i++) {
    if (i == 0) {
      list[i].index = i;
    } else {
      if (list[i - 1][value] == list[i][value]) {
        list[i].index = list[i - 1].index;
      } else {
        list[i].index = i;
      }
    }
  }
}

示例:

let arrListThree = [
      { id: 1, name: 'test1', score: 99 },
      { id: 2, name: 'test2', score: 89 },
      { id: 3, name: 'test3', score: 88 },
      { id: 4, name: 'test4', score: 85 },
      { id: 5, name: 'test5', score: 96 },
      { id: 6, name: 'test6', score: 88 },
    ]

parallelSorting(arrListThree, 'score');  // 升序
// parallelSorting(arrListThree, 'score', false);  // 降序

console.log('并列排序(升序):', arrListThree);
// console.log('并列排序(降序):', arrListThree);

在这里插入图片描述
在这里插入图片描述

3、JS实现数字每三位添加逗号

参考: JS数字每三位加逗号的最简单方法

(1)toLocaleString() 方法

toLocaleString() 方法可根据本地时间把 Date 对象转换为字符串,并返回结果。

// 根据本地时间把 Date 对象转换为字符串:
var d = new Date();
var n = d.toLocaleString();
console.log(n);  // 2024/3/21 11:46:37

还可以将数字变成千分位格式,这个方法最为简单,使用JS原生实现。toLocaleString在将数字转换为字符串的同时,会使用三位分节法进行显示。如果是浮点数,只保留小数点后三位数,并进行了四舍五入。如果对结果要求不高,这个算是最简单的实现。

let number = 12345678.10291;
console.log(number.toLocaleString()); // 12,345,678.103

(2)Intl.NumberFormat

Intl.NumberFormat 是对语言敏感的格式化数字类的构造器类。
Intl.NumberFormat 对象能使数字在特定的语言环境下格式化。

let number = 12345678.10291;

console.log(new Intl.NumberFormat('de-DE').format(number)) // 12.345.678,103
console.log(new Intl.NumberFormat('ja-JP').format(number)) // 12,345,678.103
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number)) // 1,23,00,000

(3)正则表达式

<script>
function thousands(num) {
	var str = num.toString();
    var reg =
        str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
    return str.replace(reg, "$1,");
}

let number = 12345678.10291;
console.log(thousands(number));  // 12,345,678.10291

</script>

4、JS 实现根据日期和时间进行排序

参考: JS数组对象——根据日期进行排序Date.parse(),按照时间进行升序或降序排序localeCompare()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(1)根据数字大小排序

/**
 * @description 1.封装数组对象的排序方法
 * @param {Object[]} dataList - 要排序的数组
 * @param {string} prop - 传入需要排序的字段
 * @param {boolean} bol - true: 升序;false: 降序;默认为true 升序
 * @return {Object[]} dataList - 返回改变完顺序的数组
 */
function compare(dataList, prop, bol = true) {
  dataList.sort(function (a, b) {
    if (bol) {
      return a[prop] - b[prop];  // 升序
    } else {
      return b[prop] - a[prop];  // 降序
    }
  });

  return dataList;
}

示例: 从大到小排序

let arrList = [
      { id: 1, name: 'test1', score: 99, time: '2024-03-25 13:51:03' },
      { id: 2, name: 'test2', score: 89, time: '2024-03-24 23:01:52' },
      { id: 3, name: 'test3', score: 102, time: '2024-03-15 01:51:12' },
      { id: 4, name: 'test4', score: 100, time: '2024-03-23 10:30:39' },
      { id: 5, name: 'test5', score: 111, time: '2024-03-23 11:21:42' },
    ]
// console.log(compare(arrList, 'score'));  // 升序
console.log(compare(arrList, 'score', false));  // 降序

在这里插入图片描述

(2)根据日期排序

/**
 * @description 2.根据日期时间混合排序
 * @param {Object[]} dataList - 要排序的数组
 * @param {string} property - 传入需要排序的字段
 * @param {boolean} bol - true: 升序;false: 降序;默认为true 升序
 * @return {Object[]} dataList - 返回改变完顺序的数组
 */
function dateSort(dataList, property, bol = true) {
  dataList.sort(function (a, b) {
    if (bol) {
      // return a[property].localeCompare(b[property]); // 升序
      return Date.parse(a[property]) - Date.parse(b[property]);  // 升序
    } else {
      // return b[property].localeCompare(a[property]); // 降序
      return Date.parse(b[property]) - Date.parse(a[property]);  // 降序
    }
  })
  return dataList;
}

示例:

let arrList = [
      { id: 1, name: 'test1', score: 99, dateTime: '2024-03-25 13:51:03' },
      { id: 2, name: 'test2', score: 89, dateTime: '2024-03-24 23:01:52' },
      { id: 3, name: 'test3', score: 102, dateTime: '2024-03-15 01:51:12' },
      { id: 4, name: 'test4', score: 100, dateTime: '2024-03-23 10:30:39' },
      { id: 5, name: 'test5', score: 111, dateTime: '2024-03-23 11:21:42' },
    ]
// console.log('升序:', dateSort(arrList, 'dateTime')); // 升序
console.log('降序:', dateSort(arrList, 'dateTime', false)); // 降序

在这里插入图片描述
在这里插入图片描述

(3)分别根据日期和时间进行排序

/**
 * @description 3.分别根据日期和时间进行排序
 * @param {Object[]} dataList - 要排序的数组
 * @param {string} property1 - 传入需要排序的字段1
 * @param {string} property2 - 传入需要排序的字段2
 * @param {boolean} bol - true: 升序;false: 降序;默认为true 升序
 * @return {Object[]} dataList - 返回改变完顺序的数组
 */
function dateSortTwo(dataList, property1, property2, bol = true) {
  dataList.sort(function (a, b) {
    if (bol) {
      return a[property1].localeCompare(b[property1]) || a[property2].localeCompare(b[property2]); // 升序
    } else {
      return b[property1].localeCompare(a[property1]) || b[property2].localeCompare(a[property2]); // 降序
    }
  })
  return dataList;
}

示例:

let arrListTwo = [
      { id: 1, name: "test1", date: '2024-03-25', time: '10:20:12' },
      { id: 2, name: "test2", date: '2024-03-24', time: '22:19:31' },
      { id: 3, name: "test3", date: '2024-03-24', time: '20:45:17' },
      { id: 4, name: "test4", date: '2024-03-26', time: '09:36:22' },
      { id: 5, name: "test5", date: '2024-03-25', time: '14:10:46' },
      { id: 6, name: "test6", date: '2024-03-26', time: '08:27:38' },
    ]

console.log('升序:', dateSortTwo(arrListTwo, 'date', 'time')); // 升序
// console.log('降序:', dateSortTwo(arrListTwo, 'date', 'time', false)); // 降序

在这里插入图片描述
在这里插入图片描述

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13283.html
标签
评论
发布的文章

jQuery 选择器

2024-05-12 00:05:34

Vue中public/assets目录区别

2024-07-02 23:07:29

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!