Hubspot custom coded workflow to convert datetime to date

by Remy Pereira on 14th February 2023

Hubspot has two types of properties related to date - date and datetime

Date properties will only store the date, and must be set to midnight UTC for the date you want. For example, Jul 5 2020 would be 1593903600 (01 May 2015 00:00:00 UTC). If you try to set a value that is not midnight UTC, you will receive an error.

This workflow converts a datetime field to date and stores in a date field. This script uses Node.js 16.x

const hubspot = require('@hubspot/api-client');

// wfkey is your private app secret token
exports.main = async (event, callback) => {
const hubspotClient = new hubspot.Client({
    accessToken: process.env.wfkey
  });
  
  let temp;
  
  // Text property lastordered_text
  try {
    const ApiResponse = await hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["lastordered_text"]);
    temp = ApiResponse.properties.lastordered_text;
  } catch (err) {
    console.error(err);
    throw err;
  }
  
  // Format the data to reset timestamp to 00:00:00
  var dateString = temp;
  dateString = dateString.split('T')[0];
  var date = new Date(dateString);
 callback({
    outputFields: {
      date: date
    }
  });
    const properties = {
  "lastordered": date
};

const SimplePublicObjectInput = { properties };

// Update the field with formatted data
 try {
  const apiResponse = await hubspotClient.crm.contacts.basicApi.update(event.object.objectId, SimplePublicObjectInput);
  console.log(JSON.stringify(apiResponse.body, null, 2));
 } catch (e) {
  e.message === 'HTTP request failed'
    ? console.error(JSON.stringify(e.response, null, 2))
    : console.error(e)
 }
}

Post a comment

Comments

Nothing yet..be the first to share wisdom.