I’m working on a project where I’m pulling data from Google Sheets into an HTML table. I’ve run into a problem with one of the cells that contains time info. For some reason, I’m getting the full date and time instead of just the time.
I’ve dealt with this exact issue before in a project. The problem stems from how Google Sheets handles date-time data internally. A quick fix is to use the JavaScript Date object’s methods directly on your data.
Try modifying your code like this:
let dateObj = new Date(rawData[row][col]);
let formattedTime = dateObj.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
console.log('Formatted time: ' + formattedTime);
let htmlRow = '<tr><td>' + rawData[0][col] + '</td><td>' + formattedTime + '</td></tr>';
tableHtml += htmlRow;
This approach uses toLocaleTimeString() with specific options to format the time exactly as you need it, without any date information. It’s cleaner and more reliable than manually extracting hours and minutes.
I’ve encountered a similar issue when working with Google Sheets and time formatting. The key is to understand that Google Sheets stores dates and times as serial numbers, which can cause confusion when extracting just the time.
Here’s a solution that worked for me:
Instead of using Utilities.formatDate(), try using the built-in getHours() and getMinutes() methods on the Date object. You can create a Date object from your rawData[row][col] value, then extract just the time components.
Here’s how you could modify your code:
let dateObj = new Date(rawData[row][col]);
let hours = dateObj.getHours().toString().padStart(2, '0');
let minutes = dateObj.getMinutes().toString().padStart(2, '0');
let formattedTime = hours + ':' + minutes;
This approach should give you the time in the format you want (15:30) without any date information. The padStart() method ensures you always get two digits for hours and minutes.