You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JSON文件读取日期范围并存储到JS变量中?

How to Fetch Date Range from JSON and Run Code in That Range

Hey there! Let's walk through exactly how to pull those dates from your JSON file, store them in JavaScript variables, and then execute code only when the current date falls within that range. I'll cover both browser and Node.js environments since you didn't specify which one you're using.

Step 1: Make Sure Your JSON File is Structured Correctly

First, let's assume your JSON file (let's call it date-range.json) looks something like this—simple and easy to parse:

{
  "startDate": "2024-06-01",
  "endDate": "2024-06-30"
}

Stick to the ISO date format (YYYY-MM-DD) here because JavaScript's Date object can parse it reliably without extra work.

Step 2: Fetch the JSON and Store Dates in JS Variables

For Browser Environments (Frontend)

Use the built-in fetch API to load the JSON file, then parse it and convert the date strings into Date objects:

// Fetch the JSON file
fetch('./date-range.json')
  .then(response => {
    if (!response.ok) throw new Error('Failed to load date range');
    return response.json();
  })
  .then(dateData => {
    // Convert JSON date strings to Date objects
    const startDate = new Date(dateData.startDate);
    const endDate = new Date(dateData.endDate);

    // Now run your date-range check and code
    executeCodeInRange(startDate, endDate);
  })
  .catch(err => console.error('Error:', err));

function executeCodeInRange(start, end) {
  // Get current date (strip time to avoid issues with time of day)
  const today = new Date();
  const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  
  // Normalize start/end dates to ignore time too
  const normalizedStart = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const normalizedEnd = new Date(end.getFullYear(), end.getMonth(), end.getDate());

  // Check if today is within the range
  if (currentDate >= normalizedStart && currentDate <= normalizedEnd) {
    // ✅ Run your code here!
    console.log('Running code inside the specified date range');
    // Example: submitForm(), updateUI(), etc.
  } else {
    console.log('Current date is outside the range—skipping code execution');
  }
}

For Node.js Environments (Backend)

Use Node's fs.promises module to read the JSON file asynchronously, then parse it just like in the browser:

const fs = require('fs').promises;

async function loadDatesAndExecute() {
  try {
    // Read and parse the JSON file
    const rawData = await fs.readFile('./date-range.json', 'utf8');
    const dateData = JSON.parse(rawData);

    // Store dates as Date objects
    const startDate = new Date(dateData.startDate);
    const endDate = new Date(dateData.endDate);

    // Run the range check
    executeCodeInRange(startDate, endDate);
  } catch (err) {
    console.error('Error loading date range:', err);
  }
}

function executeCodeInRange(start, end) {
  const today = new Date();
  const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const normalizedStart = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const normalizedEnd = new Date(end.getFullYear(), end.getMonth(), end.getDate());

  if (currentDate >= normalizedStart && currentDate <= normalizedEnd) {
    // ✅ Execute your backend code here
    console.log('Running backend code within the date range');
    // Example: sendEmail(), syncDatabase(), etc.
  } else {
    console.log('Date is out of range—code will not run');
  }
}

// Kick off the process
loadDatesAndExecute();

Key Notes to Avoid Bugs

  • Normalize Dates: By stripping the time component (hours/minutes/seconds), you ensure that even if today is 3 PM and your start date is midnight, it still counts as within the range.
  • Error Handling: Always add catch blocks to handle cases where the JSON file is missing, malformed, or the dates are invalid.
  • Date Format: Stick to ISO 8601 (YYYY-MM-DD) for your JSON dates—this avoids cross-browser/Node parsing issues.

内容的提问来源于stack exchange,提问作者Alex111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:50:07