js制作柱状图的x轴时间, 分别展示 月/周/日 的数据

背景

有个需求是要做一个柱状图, x 轴是时间, y 轴是数量. 其中 x 轴的时间有三种查看方式: 月份/周/日, 也就是分别查看从当前日期开始倒推的最近每月/每周/每日的数量.

本篇文章主要是用来制作三种不同的 x 轴

从当前月开始倒推月份

注意 getMonth() 函数可以获取当前月份, 但是范围是 0-11, 0代表1月

let xArr = []; // 用来存放周的数组(x轴的坐标)
let xNum = 4; // x轴展示// 获取当前时间
let today = new Date();// 格式化x轴坐标
const XMonthFormat = (year,month) => {return year+"-"+("0"+month).substr(-2)
}// 月份的返回值范围是 0~11,0是一月
const createXMonth = (today) => {let currentMonth = today.getMonth()let currentYear = today.getFullYear();for(let i = 0;i<4;i++) {let targetMonth = currentMonth - i + 1;let targetMonthEnd = currentMonth - i + 2;targetMonth <= 0 ? targetMonth += 12 : targetMonth;targetMonthEnd <= 0 ? targetMonth += 12 : targetMonthEnd;if(targetMonth === 12) {if(i != 12) {currentYear--}}let monthEndYear = targetMonth > targetMonthEnd ? currentYear + 1 : currentYear;xArr.push({thisMonthStart:XMonthFormat(currentYear,targetMonth),thisMonthEnd: XMonthFormat(monthEndYear,targetMonthEnd)})}
}createXMonth(today)

结果:
在这里插入图片描述

从当前日开始倒推

为了避免不同日期不同, 所以采用了getTime() 这种方式

let xArr = []; // 用来存放周的数组(x轴的坐标)
let xNum = 4; // x轴展示// 获取当前时间
let today = new Date();// 格式化x轴坐标
const XDayFormat = (day) => {let dayStr = day.toISOString().substring(0, 10)return dayStr
}// 获取前一天的日期
const oneDaysAgo = (curDate) => new Date(curDate.getTime() - 1 * 24 * 60 * 60 * 1000)const createXDay = (curDay) => {xArr.push(XDayFormat(curDay))if(xArr.length < xNum) {createXDay(oneDaysAgo(curDay))}
}
createXDay(today)

结果:
在这里插入图片描述

从当前周开始倒推

比起月/日, 周是较为复杂的. 思路是: 首先获取本周的起始时间(周一和周日), 然后分别获取周一和周日七天前的日期(也就是上一周的起止日期), 根据要展示的 x 轴的坐标数量进行递归

首先先看两个小的 deomo

js获取本周起止时间

// 获取当前时间
var today = new Date();// 获取本周的第一天(星期日)
var firstDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 1));// 获取本周的最后一天(星期六)
var lastDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 7));// 转换成指定格式
var firstDayOfWeekStr = firstDayOfWeek.toISOString().substring(0, 10);
var lastDayOfWeekStr = lastDayOfWeek.toISOString().substring(0, 10);console.log('本周起始日期:', firstDayOfWeekStr);
console.log('本周结束日期:', lastDayOfWeekStr);

结果为:
在这里插入图片描述

如果不截取字符串的话, 得到的结果是第一行这样的:
在这里插入图片描述

这个代码使用了 JavaScript 内置对象 Date 来获取当前时间,然后根据当前时间计算出本周的起始日期和结束日期。具体步骤如下:

  • 使用 setDate() 方法将当前日期减去星期几的天数,得到本周的第一天(按中文习惯设置为星期一)。
  • 使用 setDate() 方法再次对当前日期进行操作,将日期减去星期几的天数,然后加上 6,得到本周的最后一天(按中文习惯设置为星期日)。
    最后,使用 toISOString() 方法将日期转换为 ISO 格式的字符串,并截取前 10 个字符,即年月日部分。

请注意,这个代码获取的时间均为本地时间,如果需要使用 UTC 时间,可以使用 getUTC*() 方法来获取 UTC 时间的相关值。

js获取7天前起止时间

// 获取当前时间
var today = new Date();// 获取7天前的时间
var sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);// 转换成指定格式
var todayStr = today.toISOString().substring(0, 10);
var sevenDaysAgoStr = sevenDaysAgo.toISOString().substring(0, 10);console.log('今天:', todayStr);
console.log('7天前:', sevenDaysAgoStr);

这个代码使用了 JavaScript 内置对象 Date 来获取当前时间,然后根据当前时间计算出 7 天前的时间。最后,使用 toISOString() 方法将时间转换为 ISO 格式的字符串,并截取前 10 个字符,即年月日部分。

请注意,这个代码获取的时间均为本地时间,如果需要使用 UTC 时间,可以使用 getUTC*() 方法来获取 UTC 时间的相关值。

let xArr = []; // 用来存放周的数组(x轴的坐标)
let xNum = 4; // x轴展示// 获取当前时间
let today = new Date();// 格式化x轴坐标
const Xformat = (start,end) => {let startStr = start.toISOString().substring(0, 10)let endStr = end.toISOString().substring(0, 10)return startStr+"至"+endStr
}// 获取每个周一的7天前的时间,也就是上个周一
const sevenDaysAgo = (curDate) => new Date(curDate.getTime() - 7 * 24 * 60 * 60 * 1000)// 获取本周的第一天(星期一)
let curMonday = new Date(today.setDate(today.getDate() - today.getDay() + 1));// 获取本周的最后一天(星期日)
let curSunday = new Date(today.setDate(today.getDate() - today.getDay() + 7));const createXWeek = (curMon,curSun) => {xArr.push(Xformat(curMon,curSun))if(xArr.length < xNum) {createX(sevenDaysAgo(curMon),sevenDaysAgo(curSun))}
}createXWeek(curMonday,curSunday)console.log('xArr:', xArr);

结果:
在这里插入图片描述

根据两个demo整合得到的代码

// 格式化x轴坐标
const XWeekFormat = (start,end) => {let startStr = start.toISOString().substring(0, 10)let endStr = end.toISOString().substring(0, 10)return startStr+"至"+endStr
}// 获取每个周一的7天前的时间,也就是上个周一
const sevenDaysAgo = (curDate) => new Date(curDate.getTime() - 7 * 24 * 60 * 60 * 1000)// 获取本周的第一天(星期一)
let curMonday = new Date(today.setDate(today.getDate() - today.getDay() + 1));// 获取本周的最后一天(星期日)
let curSunday = new Date(today.setDate(today.getDate() - today.getDay() + 7));const createXWeek = (curMon,curSun) => {xArr.push(XWeekFormat(curMon,curSun))if(xArr.length < xNum) {createX(sevenDaysAgo(curMon),sevenDaysAgo(curSun))}
}createXWeek(curMonday,curSunday)

三个一起的最终js

let xArr = []; // 用来存放周的数组(x轴的坐标)
let xNum = 4; // x轴展示// 获取当前时间
let today = new Date();// --------------------- 每月 --------------------// 格式化x轴坐标
const XMonthFormat = (year,month) => {return year+"-"+("0"+month).substr(-2)
}// 月份的返回值范围是 0~11,0是一月
const createXMonth = (today) => {let currentMonth = today.getMonth()let currentYear = today.getFullYear();for(let i = 0;i<4;i++) {let targetMonth = currentMonth - i + 1;let targetMonthEnd = currentMonth - i + 2;targetMonth <= 0 ? targetMonth += 12 : targetMonth;targetMonthEnd <= 0 ? targetMonth += 12 : targetMonthEnd;if(targetMonth === 12) {if(i != 12) {currentYear--}}let monthEndYear = targetMonth > targetMonthEnd ? currentYear + 1 : currentYear;xArr.push({thisMonthStart:XMonthFormat(currentYear,targetMonth),thisMonthEnd: XMonthFormat(monthEndYear,targetMonthEnd)})}
}createXMonth(today)// ------------------------------------------// --------------------- 每日 --------------------// 格式化x轴坐标
const XDayFormat = (day) => {let dayStr = day.toISOString().substring(0, 10)return dayStr
}// 获取前一天的日期
const oneDaysAgo = (curDate) => new Date(curDate.getTime() - 1 * 24 * 60 * 60 * 1000)const createXDay = (curDay) => {xArr.push(XDayFormat(curDay))if(xArr.length < xNum) {createXDay(oneDaysAgo(curDay))}
}
// createXDay(today)
// ------------------------------------------// --------------------- 每周 --------------------// 格式化x轴坐标
const XWeekFormat = (start,end) => {let startStr = start.toISOString().substring(0, 10)let endStr = end.toISOString().substring(0, 10)return startStr+"至"+endStr
}// 获取每个周一的7天前的时间,也就是上个周一
const sevenDaysAgo = (curDate) => new Date(curDate.getTime() - 7 * 24 * 60 * 60 * 1000)// 获取本周的第一天(星期一)
let curMonday = new Date(today.setDate(today.getDate() - today.getDay() + 1));// 获取本周的最后一天(星期日)
let curSunday = new Date(today.setDate(today.getDate() - today.getDay() + 7));const createXWeek = (curMon,curSun) => {xArr.push(XWeekFormat(curMon,curSun))if(xArr.length < xNum) {createX(sevenDaysAgo(curMon),sevenDaysAgo(curSun))}
}// createXWeek(curMonday,curSunday)// ---------------------------------------------console.log('xArr:', xArr);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/142167.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【数学建模】2023华为杯研究生数学建模F题思路详解

强对流降水临近预报 我国地域辽阔&#xff0c;自然条件复杂&#xff0c;因此灾害性天气种类繁多&#xff0c;地区差异大。其中&#xff0c;雷雨大风、冰雹、龙卷、短时强降水等强对流天气是造成经济损失、危害生命安全最严重的一类灾害性天气[1]。以2022年为例&#xff0c;我国…

基于C++实现的3D野外赛车驾驶游戏源码+项目文档+汇报PPT

项目介绍&#xff1a;本项目实现了一个户外场景下的赛车游戏&#xff0c;可以通过键盘控制赛车的移动&#xff0c;视角为第二人称视角。场景中有汽车&#xff0c;建筑&#xff0c;道路&#xff0c;天空等物体&#xff0c;拥有光照和阴影的效果。通过粒子系统模拟尾气效果&#…

Spring Boot与Spring Security的跨域解决方案

目录 一、什么是跨域问题 二、Spring Boot和Spring Security介绍 三、如何解决Spring Boot与Spring Security的跨域问题 一、什么是跨域问题 跨域问题&#xff08;Cross-Origin Resource Sharing&#xff0c;简称CORS&#xff09;是指在Web开发中&#xff0c;浏览器出于安全…

vue+express、gitee pm2部署轻量服务器

一、代码配置 前后端接口都保持 127.0.0.1:3000 vue创建文件 pm2.config.cjs module.exports = {apps: [{name: xin-web, // 应用程序的名称script: npm, // 启动脚本args: run dev, // 启动脚本的参数cwd: /home/vue/xin_web, // Vite 项目的根目录interpreter: none, // 告…

[动物文学]走红年轻人化身“精神动物”,这届年轻人不想做人了

数据洞察流行趋势&#xff0c;敏锐把握流量风口。本期千瓜与您分享近期小红书八大热点内容&#xff0c;带您看热点、追热门、借热势&#xff0c;为您提供小红书营销布局风向标。 「动物文学」走红 年轻人化身“精神动物” 其实&#xff0c;这届年轻人“不想做人”很久了………

Kubernetes组件和架构简介

目录 一.概念简介 1.含义&#xff1a; 2.主要功能&#xff1a; 3.相关概念&#xff1a; 二.组件和架构介绍 1.master&#xff1a;集群的控制平面&#xff0c;管理集群 2.node&#xff1a;集群的数据平面&#xff0c;为容器提供工作环境 3.kubernetes简单架构图解 一.概…

使用vue-cli脚手架工具搭建vue工程项目以及配置路由

vue-cli是用node编写的命令行工具&#xff0c;我们需要进行全局安装。打开命令行终端&#xff0c;输入如下命令&#xff1a; 1 $ npm install -g vue-cli 这里使用的是npm&#xff0c;为了开发的便利&#xff0c;推荐安装cnpm&#xff0c;这样运行指令会更迅速&#xff0c;安…

描述符——设备描述符

文章目录 描述符定义描述符实现描述符含义 描述符定义 描述符实现 /*** brief Device descriptor.*/ typedef struct __attribute__ ((packed)) {uint8_t bLength ; /**< Size of this descriptor in bytes. */uint8_t bDescriptorType ; /**< DEVICE D…

基于springboot+vue的大学生创新创业系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 项目介绍…

Vue组件库Element

目录 Vue组件库ElementElement简介Element快速入门环境配置Element常用组件Table表格Table表格演示Table表格属性详解 Pagination分页Pagination分页演示Pagination分页属性详解Pagination分页事件详解 Dialog对话框Dialog对话框组件演示Dialog对话框属性详解 Form表单Form表单…

Chatbot UI集成LocalAI实现自托管的ChatGPT

本文比惯例提前了一天发&#xff0c;因为明天一早&#xff0c;老苏就踏上回乡的路了&#xff0c;三年没回老家&#xff0c;这次专门请了 2 天的假 难得回家&#xff0c;打算多陪陪家人&#xff0c;和多年不见的朋友聚聚&#xff0c;当然如果有网络条件&#xff0c;还是会正常发…

基于STM32的蔬菜大棚温湿度智能控制系统设计

一、前言 随着人们对健康和可持续生活方式的关注不断增加&#xff0c;蔬菜大棚成为了现代农业中的重要组成部分。蔬菜大棚提供了一个受控的环境&#xff0c;使得农民能够在任何季节种植蔬菜&#xff0c;并根据需要进行调节。为了实现最佳的蔬菜生长和产量&#xff0c;对温度和…

RedisTemplate出现\xac\xed\x00\x05t\x00\x0f前缀解决

问题描叙 出现这种乱码前缀的原因是没有进行序列化&#xff0c;因此导致在传输过程出现乱码问题&#xff0c;存到数据库&#xff0c;发现 key,hash key/value 都有 \xAC\xED\x00\x05t\x00 前缀。RedisTemplate类中默认是没有设置序列化的。 解决方法 设置RedisTemplate的序列…

微机原理与接口技术

一、微型计算机系统概述二、总线 总线(Bus)&#xff1a;是连接计算机各部件的一组公共信号线;总线上能同时传送二进制信息的位数称为总线宽度。 优点&#xff1a;大大减少传输线数目&#xff0c;结构简单&#xff0c;便于扩充 总线按传送信息分类:地址总线、数…

华为小型智能园区网络解决方案

云时代来袭&#xff0c;数字化正在从园区办公延伸到生产和运营的方方面面&#xff0c;智慧校园&#xff0c;柔性制造&#xff0c;掌上金融和电子政务等&#xff0c;面对各种各样的新兴业态的涌现&#xff0c;企业需要构建一张无所不联、随心体验、业务永续的全无线网络&#xf…

burpsuite只有intruder中文乱码

burpsuite 只有intruder模块中文乱码 现象&#xff1a;解决方案 现象&#xff1a; 在proxy、repeater等模块下中文均可正常显示&#xff0c;如下图&#xff1a; 在intruder模块&#xff0c;中文显示乱码 解决方案 在payloads标签下payload processing中添加“Decode”

web服务基础

前言&#xff1a;web服务怎么做&#xff0c;怎样使用&#xff0c;这是一个长期的任务 1、DNS解析原理 在windows 客户端查看本地缓存的DNS解析记录 C:\Users\86157>ipconfig /displaydns #其中这两个字符之间会有空格 在windows11 中的命令行运行结果如下 清除win客户端…

【区块链 | DID】白话数字身份

《十四五数字经济发展规划》提出建立健全政务数据共享协调机制&#xff0c;加快数字身份统一认证和电子证照、电子签章、电子公文等互信互任&#xff0c;推进发票电子化改革&#xff0c;促进政务数据共享、流程优化和业务协同。在数字经济逐渐成形的背景下&#xff0c;推进数字…

Elasticsearch 集群时的内部结构是怎样的?

Apache Lucene : Flush, Commit Elasticsearch 是一个基于 Apache Lucene 构建的搜索引擎。 它利用 Lucene 的倒排索引、查询处理和返回搜索结果等功能来执行搜索。 它还扩展了 Lucene 的功能&#xff0c;添加分布式处理功能以支持大型数据集的搜索。 让我们看一下 Apache Luc…

Learn Prompt- Midjourney Prompt:Prompt 提示语

基础结构​ 一个基本的提示可以简单到一个单词、短语或表情符号。非常短的提示将在很大程度上依赖于 Midjourney 的默认样式。 完整 prompt&#xff1a;可以包括一个或多个图像链接、多个文本短语或单词&#xff0c;以及一个或多个后缀参数 Image Prompts: 可以将图像 URL 添加…