Why does my custom code return invalid dates in HubSpot?

Hi All,

Apologies Im not really a developer but Ive managed to do this custom coding to roll up closed won start and end dates from deals to company level so I can see their start date and their end dates through their time. I will attach the code below however despite having successful outputs that match exactly to my date pickers formats it keeps saying invalid dates in tests? Apologies for the long message in advance

const axios = require(‘axios’);

exports.main = async (event, callback) => {
const companyId = event.inputFields[‘hs_object_id’];
const apiKey = process.env.HAPIKEY;

const headers = {
Authorization: `Bearer ${apiKey}`,
‘Content-Type’: ‘application/json’
};

try {
const requestBody = { inputs: [{ id: companyId.toString() }] };
console.log(‘Requesting batch associations with body:’, JSON.stringify(requestBody));

const batchRes = await axios.post(
‘https://api.hubapi.com/crm/v3/associations/company/deal/batch/read’,
requestBody,
{ headers }
);

const dealIds = batchRes.data.results[0]?.to?.map(d => d.id) || [];
console.log(‘Associated deal IDs:’, dealIds.join(', '));

if (dealIds.length === 0) {
return callback({
outputFields: {
start_date: null,
end_date: null
}
});
}

let earliestStart = null;
let latestEnd = null;

for (const dealId of dealIds) {
const dealRes = await axios.get(
`https://api.hubapi.com/crm/v3/objects/deals/${dealId}?properties=dealstage,contract_start_date,contract_end_date__ced_`,
{ headers }
);

const props = dealRes.data.properties;
console.log(`Deal ${dealId} properties:`, props);

if (props.dealstage !== ‘757916358’) {
console.log(`Deal ${dealId} is not in target dealstage.`);
continue;
}

const start = props.contract_start_date ? new Date(props.contract_start_date) : null;
const end = props.contract_end_date__ced_ ? new Date(props.contract_end_date__ced_) : null;

if (!start || !end) {
console.log(`Deal ${dealId} missing start or end date.`);
continue;
}

if (!earliestStart || start < earliestStart) earliestStart = start;
if (!latestEnd || end > latestEnd) latestEnd = end;
}

// Format date as DD/MM/YYYY (with slashes)
const format = date => {
const dd = String(date.getDate()).padStart(2, ‘0’);
const mm = String(date.getMonth() + 1).padStart(2, ‘0’);
const yyyy = date.getFullYear();
return `${dd}/${mm}/${yyyy}`; // <-- day first with slashes
};

const output = {
start_date: earliestStart ? format(earliestStart) : null,
end_date: latestEnd ? format(latestEnd) : null
};

console.log(‘Final Output Fields:’, output);

return callback({ outputFields: output });
} catch (error) {
console.error(‘Custom code error:’, error.response?.data || error.message);
return callback({
outputFields: {
start_date: null,
end_date: null
}
});
}
};

Date and datetime values need to be passed in a format compatible with the specific HubSpot property or workflow output type; date and datetime outputs are distinct types, and timestamps can be used where a timestamp is expected.

You would need to convert your output to unix timestamp (milliseconds format) for it to work properly.

Moderator Note: this post was reviewed for relevancy and optimized for clarity on September 30, 2026. Thank you for your contributions to the HubSpot Community!

Thank you for the info! Not sure if at this point its a bug, but changed it in the code, and then re-added the output to the fields and still saying invalid date, unless do I need to programme it so the output says ms as well?

I made a simple workflow on my dev account to try to test this.

Test mode seems like it does not work or returns a bad result. It might be because you’re using output fields from a custom coded action so the test doesn’t see the actual output (doesn’t process the code) and sets the fields to null so it considers it invalid.

When I manually enrolled a record, it seemed to work fine although a date field seems to be super finicky (requires the time portion of the stamp to be midnight or it’ll error out).

I faced a similar issue where the date output was returning as “Invalid Date.” In my case, it was due to the incorrect date format being passed from the API response. Make sure you’re using a standard ISO 8601 date format (YYYY-MM-DDTHH:mm:ssZ) before parsing it. Also, double-check if the field you’re accessing actually has a valid date value assigned. Converting the date to a universal format on the backend solved it for me. Hope this helps!
https://developers.hubspot.com/docs/guides/api/crm/properties#add-values-to-date-and-datetime-proper…

Hi @DCrinnion1

"I believe you are reading company property and want to update the deal [property, id so, you need to change the date format to timestamp and send that value to update the deal property.

I hope this will help you out. Please mark it as Solution Accepted and upvote to help another Community member.
Thanks!

Hi @GRajput,
Thank you for sharing your insights!
Cassie, Community Manager