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

实体每日工作时长与设备日期时段比对及JSON存储方案咨询

Optimal JSON Structure for Daily Working Hours & Comparison with Device Data

Great question! Let's tackle this step by step—first the best way to store daily working hours in JSON, then how to compare that data with your device's date (day of week + time slot) information.


1. Optimal JSON Structure for Daily Working Hours

Your initial idea of a key-value mapping is solid, but there are a few variations depending on your business needs. Here are the most common and effective approaches:

Option 1: Basic Key-Value Mapping (Best for Simple Single-Shift Scenarios)

This is the most straightforward approach—map each day of the week directly to its working hours string. It’s easy to read, parse, and update.

{
  "working_hours": {
    "MONDAY": "09:00-18:00",
    "TUESDAY": "09:00-18:00",
    "WEDNESDAY": "09:00-17:00",
    "THURSDAY": "09:00-18:00",
    "FRIDAY": "09:00-16:00",
    "SATURDAY": "closed",
    "SUNDAY": "closed"
  }
}
  • Pros: Intuitive, minimal overhead, perfect for entities with one daily shift or clear "closed" status.
  • Tips: Stick to a consistent key format (e.g., all uppercase English day names, or numeric codes like 1 for Monday) to avoid parsing errors. Use "closed" or null for non-working days, depending on what your system expects.

Option 2: Structured Array (Best for Multi-Shift or Complex Scenarios)

If your entities have split shifts (e.g., morning and afternoon with a lunch break) or need extra metadata (like holiday flags, lunch hours), an array of objects is far more flexible.

{
  "working_hours": [
    {
      "day_of_week": "MONDAY",
      "periods": [
        {"start": "09:00", "end": "12:30"},
        {"start": "13:30", "end": "18:00"}
      ],
      "is_holiday": false
    },
    {
      "day_of_week": "SATURDAY",
      "periods": [],
      "is_holiday": true
    }
  ]
}
  • Pros: Extensible (add notes, break times, or holiday status later), supports multiple shifts per day.
  • Minor Cons: Requires a quick loop to find the relevant day, but modern JSON parsers handle this with negligible overhead.

Option 3: Numeric Index Mapping (Best for Space-Sensitive Use Cases)

If you need to minimize payload size (e.g., for IoT devices with limited bandwidth), use numeric codes for days (e.g., 1 = Monday, 7 = Sunday) instead of full names.

{
  "working_hours": {
    "1": "09:00-18:00",
    "2": "09:00-18:00",
    "3": "09:00-17:00",
    "4": "09:00-18:00",
    "5": "09:00-16:00",
    "6": "closed",
    "7": "closed"
  }
}
  • Pros: Smaller payload size, faster transmission.
  • Cons: Less readable—make sure to document the numeric-day mapping clearly for your team.

Recommendation

Go with the basic key-value mapping if you only need to track single shifts or closed days. Use the structured array if you anticipate complex scheduling needs down the line. The numeric index is only worth it if bandwidth is a critical constraint.


2. Comparing JSON Working Hours with Device Date/Time Data

Assuming your device returns data like {"current_day": "MONDAY", "current_time": "14:30"} (or a timestamp you can convert to day/time), here’s how to handle the comparison:

Step-by-Step Logic

  1. Normalize Formats: Ensure the device’s day name matches your JSON’s key format (e.g., both uppercase MONDAY instead of mixing Monday or mon). Convert the device’s time to a consistent HH:mm format.
  2. Fetch Relevant Hours: Pull the working hours for the device’s current day from your JSON.
  3. Check Time Against Shift(s):
    • For single-shift strings: Split the string into start/end times, convert both to total minutes (e.g., 09:00 = 540 minutes), then check if the current time falls between them.
    • For multi-shift arrays: Loop through each period and check if the current time is in any of the windows.
    • For closed days: Immediately return "not in working hours".

Example Code (JavaScript)

Here’s a practical implementation for the basic key-value structure:

// JSON data (fetched from your source)
const entityWorkingHours = {
  "working_hours": {
    "MONDAY": "09:00-18:00",
    "SATURDAY": "closed"
  }
};

// Device-provided data
const deviceData = {
  currentDay: "MONDAY",
  currentTime: "14:30"
};

// Helper: Convert HH:mm string to total minutes (easier for comparison)
const timeToMinutes = (timeStr) => {
  const [hours, minutes] = timeStr.split(":").map(Number);
  return hours * 60 + minutes;
};

// Core comparison function
const isWithinWorkingHours = () => {
  const dayHours = entityWorkingHours.working_hours[deviceData.currentDay];
  
  // Handle closed days
  if (!dayHours || dayHours === "closed") return false;
  
  // Split start/end times and convert to minutes
  const [startStr, endStr] = dayHours.split("-");
  const startMinutes = timeToMinutes(startStr);
  const endMinutes = timeToMinutes(endStr);
  const currentMinutes = timeToMinutes(deviceData.currentTime);
  
  // Check if current time is in the window
  return currentMinutes >= startMinutes && currentMinutes <= endMinutes;
};

console.log(isWithinWorkingHours()); // Output: true

For the multi-shift array structure, adjust the comparison function like this:

const entityWorkingHoursArray = {
  "working_hours": [
    {
      "day_of_week": "MONDAY",
      "periods": [{"start": "09:00", "end": "12:30"}, {"start": "13:30", "end": "18:00"}]
    }
  ]
};

const isWithinWorkingHours = () => {
  const dayEntry = entityWorkingHoursArray.working_hours.find(
    item => item.day_of_week === deviceData.currentDay
  );
  
  if (!dayEntry || dayEntry.periods.length === 0) return false;
  
  const currentMinutes = timeToMinutes(deviceData.currentTime);
  
  // Check if current time falls in any period
  return dayEntry.periods.some(period => {
    const start = timeToMinutes(period.start);
    const end = timeToMinutes(period.end);
    return currentMinutes >= start && currentMinutes <= end;
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:21:15