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

如何在JavaScript中从DynamoDB时间戳字符串提取日期时间用于散点图?

How to Split Timestamp String into Date and Time for Google Scatter Charts

Got it, let's work through this. The core problem with your current code is that toLocaleDateString and toLocaleTimeString return strings, but Google Scatter Charts expects a Date object for the X-axis (date column) and a numeric value for the Y-axis (time column). Let's fix this step by step.

First, Parse the Timestamp String Correctly

Your DynamoDB timestamp is in "2018.01.16 14:35:40" format. First, we need to convert this string into a proper JavaScript Date object. Splitting the string into date and time components avoids browser parsing inconsistencies:

const timestampStr = iotButton.TimeStamp; // Your timestamp string from DynamoDB
const [datePart, timePart] = timestampStr.split(' ');

// Split date into year, month, day (convert to numbers)
const [year, month, day] = datePart.split('.').map(Number);
// Split time into hours, minutes (we can ignore seconds for your use case)
const [hours, minutes] = timePart.split(':').map(Number);

// Important: JavaScript months are 0-indexed (January = 0, not 1!)
const fullDate = new Date(year, month - 1, day, hours, minutes);

Extract Date for X-axis

For the X-axis, create a new Date object that only includes the year, month, and day (set time to midnight to ensure consistency):

const clickDate = new Date(fullDate.getFullYear(), fullDate.getMonth(), fullDate.getDate());

Convert Time to Numeric Value for Y-axis

Google Charts requires the Y-axis to be a number. Convert the time to total minutes since midnight (this makes it easy to format back to a time string later):

// Total minutes = hours * 60 + minutes
const clickTime = hours * 60 + minutes;

Update Your Full Code

Another fix: you're calling drawChart for every single item, which redraws the chart each time. Instead, collect all data points first, then draw the chart once. Here's the revised code:

function onScan(err, data) {
  if (err) {
    document.getElementById('textarea').innerHTML += "Unable to scan the table: " + "\n" + JSON.stringify(err, undefined, 2);
  } else {
    // Collect all data points first
    const chartDataPoints = [];
    
    data.Items.forEach(function (iotButton) {
      const timestampStr = iotButton.TimeStamp;
      const [datePart, timePart] = timestampStr.split(' ');
      const [year, month, day] = datePart.split('.').map(Number);
      const [hours, minutes] = timePart.split(':').map(Number);
      
      // X-axis: Date object with only year/month/day
      const clickDate = new Date(year, month - 1, day);
      // Y-axis: Numeric time (total minutes since midnight)
      const clickTime = hours * 60 + minutes;
      
      chartDataPoints.push([clickDate, clickTime]);
    });
    
    // Draw the chart with all data points
    drawChart(chartDataPoints);
  }
}

google.charts.load('current', {'packages': ['scatter']});
// Wait for scan to complete before drawing, or initialize empty
google.charts.setOnLoadCallback(function() {
  // Optional: Initialize with empty chart if needed
});

function drawChart(chartData) {
  var data = new google.visualization.DataTable();
  data.addColumn('date', 'Date');
  data.addColumn('number', 'Time');
  data.addRows(chartData);
  
  var options = {
    width: 700,
    height: 500,
    chart: {
      title: 'Rundzeiten nach Messzeitpunkt'
    },
    hAxis: {title: 'Date'},
    vAxis: {
      title: 'Time',
      // Format the numeric minutes back to a readable time string
      format: 'HH:mm',
      // Optional: Add custom ticks for better readability
      ticks: [0, 360, 720, 1080, 1440] // Midnight, 6AM, Noon, 6PM, Midnight
    }
  };
  
  var chart = new google.charts.Scatter(document.getElementById('scatterchart_material'));
  chart.draw(data, google.charts.Scatter.convertOptions(options));
}

Key Tips to Remember

  • 0-indexed Months: JavaScript Date months start at 0 (January = 0), so always subtract 1 from the month value parsed from your string.
  • Batch Processing: Collecting all data points before drawing the chart is more efficient than redrawing for every item.
  • Y-axis Formatting: The format: 'HH:mm' option in vAxis converts the numeric minute value back into a human-readable time, so your chart will show times like "14:35" instead of raw numbers.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:24:39