如何从JSON文件读取日期范围并存储到JS变量中?
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

