Probably a newb question, but I need help with date formats... help?

SOLVE
SaleProcessNerd
Participant

Off the start, I thank you for your patience. I am a sales guy that talked himself into a RevOps role and I'm literally breaking my teeth in coding wise with the coded workflow feature.

So......

 

I'm trying to take a date that was copied into a custom date field ( 'test') , add a year to it, and update that field (in a deal).

 

 

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

exports.main = (event, callback) => {
  callback(processEvent(event));
};

function processEvent(event) {
  const hubspotClient = new hubspot.Client({ apiKey: process.env.WhiteRabbit });

  let dealId = event.object.objectId;

  hubspotClient.crm.deals.basicApi
    .getById(dealId, ['test'])
    .then(results => {
     let dateString = results.body.properties['test'];

      hubspotClient.crm.deals.basicApi
        .update(
          dealId,
          {
            properties: {
              ['test']: addYear(dateString)
            }
          }
        )
    });
}
function addYear(dateString) {
const date = new Date(dateString);
const year = date.getFullYear() + 1;
const month = date.getMonth() + 1;
const day = date.getDate();
return date __________?
;
//return    month + '/' + day + '/' + year  ->date format error
//return    `${year}/${month}/${day}`       ->date format error
//return    date.toUTCString()              -> not a function
//return.   date.toISOString()              -> not a function

 

 

 

 

 

I can't seem to figure out how to format this new date so hubstop will accept it. I  run into:
[{\“isValid\“:false,\“message\“:\“2022/2/28 was not a valid long......

 

 

 

Help?

0 Upvotes
2 Accepted solutions

Accepted Solutions
sam-g
Solution
Contributor

Yes, sorry I just set a value there for testing - the sample value you provided.

 

I made one tweak to the if condition:

 

let dateString = 1614470400000;
let newDate = addMonths(dateString,12);
console.log(newDate); // just to check

newDate = newDate.getTime()
console.log(newDate);

function addMonths(date, months) {
    var od = new Date(date);
  	var nd = new Date(date);    
    var od_m = od.getMonth();
    od.setMonth(od_m + months);
		if (od.getDate() != nd.getDate()) {
      od.setDate(0);
    }
    return od;
}

 

When I run with the input you provided `1614470400000` I get `1646006400000` as the output for the new date. If you put those values in an epoch time converter you get:

 

Sunday, February 28, 2021 12:00:00 AM

Monday, February 28, 2022 12:00:00 AM

 

The if condition sets the date to the last day of the prior month in the case where the month in the new date has fewer days than the month in the original date.

 

You can try it here in JsFiddle: https://jsfiddle.net/ktc8jgpn/1/

 

Open your console when you run it.

View solution in original post

0 Upvotes
SaleProcessNerd
Solution
Participant

EDIT: Thank you so much. Here is the finished and functional code. Much appreciated for all the help.

 

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

exports.main = (event, callback) => {
  callback(processEvent(event));
};

function processEvent(event) {
  const hubspotClient = new hubspot.Client({ apiKey: process.env.WhiteRabbit });

  let dealId = event.object.objectId;

  hubspotClient.crm.deals.basicApi
    .getById(dealId, ['test'])
    .then(results => {
let dateString = results.body.properties['test'];
let newDate = addMonths(dateString,12);
console.log(newDate); 
  
    hubspotClient.crm.deals.basicApi
        .update(
          dealId,
          {
            properties: {
              ['test']: addMonths(dateString, 12)
}
          }
        )
    });
}
function addMonths(date, months) {
	var od = new Date(date);
	var nd = new Date(date);    
	var od_m = od.getMonth();
    od.setMonth(od_m + months);
		if (od.getDate() != nd.getDate()) {
      od.setDate(0);
    }
    return od;
}

 

View solution in original post

0 Upvotes
12 Replies 12
sam-g
Contributor

Can you provide a sample value that you are passing in to this function?

SaleProcessNerd
Participant
"test": {
			"value": "1614470400000",
			"timestamp": 1612500607106,
			"source": "AUTOMATION_PLATFORM",
			"sourceId": "enrollmentId:74194266557;actionExecutionIndex:0",
			"updatedByUserId": null,
			"versions": [
				{
					"name": "test",
					"value": "1614470400000",
					"timestamp": 1612500607106,
					"sourceId": "enrollmentId:74194266557;actionExecutionIndex:0",
					"source": "AUTOMATION_PLATFORM",
					"sourceVid": []
				}
			]
0 Upvotes
zeke
HubSpot Product Team

I think what you're looking for is `date.getTime()`. This will return the value as an EPOCH timestamp, which is what HubSpot uses internally for dates! 

sam-g
Contributor

@SaleProcessNerd - I think there may be a bit of confusion here - you have a value in the `test` field on your deal object that contains a an EPOCH timestamp like in your example above: 

 

 

1614470400000

 

 

This value already has a year in it, it's part of the timestamp.

 

Are you trying to convert this value into just a human readable year and replace your original value in test with that? Or are you trying to extract the year and put it into another field on the record?

0 Upvotes
SaleProcessNerd
Participant

Ultimately I'm trying to take the date value from the field 'Close Date' ( 'closedate' is the HS internal name), add one year to it, and put it into a custom date field 'test' so that new date field 'test' shows a date one year from the Deal's 'Close Date'.

The current code above assumes that the date value from 'Close Date' has been copied into the 'test' field prior to the script step, but it doesnt have to be.

0 Upvotes
sam-g
Contributor

@SaleProcessNerd - I think it would be more efficient to do that all in one coded step (get the close date value and then add the year to the test property), but to just add a year to a date you could use this function:

 

let dateString = results.body.properties['test'];
let newDate = addMonths(dateString,12);
console.log(dateString, newDate) // just to check

function addMonths(date, months) {
    var d = date.getDate();
    date.setMonth(date.getMonth() + +months);
    if (date.getDate() != d) {
      date.setDate(0);
    }
    return date;
}

 

Then just set your test property to the newDate value.

0 Upvotes
SaleProcessNerd
Participant

This is the error I got: 

ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: date.getDate is not a function","reason":{"errorType":"TypeError","errorMessage":"date.getDate is not a function","stack":["TypeError: date.getDate is not a function","    at addMonths

0 Upvotes
sam-g
Contributor

@SaleProcessNerd - dates are always fun to work with 🙂

 

Try this out:

 

let dateString = 1614470400000;
let newDate = addMonths(dateString,12);
console.log(newDate); // just to check

newDate = newDate.getTime()
console.log(newDate);

function addMonths(date, months) {
    var od = new Date(date);
  	var nd = new Date(date);    
    var od_m = od.getMonth();
    od.setMonth(od_m + months);
    if (od.getDate() != nd) {
      od.setDate(0);
    }
    return od;
}
0 Upvotes
SaleProcessNerd
Participant

Well at least I didnt get an error this time, however it didnt add a year to the 'test' field. I appreciate all your help and patience with this.

Also, why have a set value for 

let dateString = 1614470400000

 Wouldnt I want that to still reference whatever value came from that field?

0 Upvotes
sam-g
Solution
Contributor

Yes, sorry I just set a value there for testing - the sample value you provided.

 

I made one tweak to the if condition:

 

let dateString = 1614470400000;
let newDate = addMonths(dateString,12);
console.log(newDate); // just to check

newDate = newDate.getTime()
console.log(newDate);

function addMonths(date, months) {
    var od = new Date(date);
  	var nd = new Date(date);    
    var od_m = od.getMonth();
    od.setMonth(od_m + months);
		if (od.getDate() != nd.getDate()) {
      od.setDate(0);
    }
    return od;
}

 

When I run with the input you provided `1614470400000` I get `1646006400000` as the output for the new date. If you put those values in an epoch time converter you get:

 

Sunday, February 28, 2021 12:00:00 AM

Monday, February 28, 2022 12:00:00 AM

 

The if condition sets the date to the last day of the prior month in the case where the month in the new date has fewer days than the month in the original date.

 

You can try it here in JsFiddle: https://jsfiddle.net/ktc8jgpn/1/

 

Open your console when you run it.

View solution in original post

0 Upvotes
SaleProcessNerd
Solution
Participant

EDIT: Thank you so much. Here is the finished and functional code. Much appreciated for all the help.

 

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

exports.main = (event, callback) => {
  callback(processEvent(event));
};

function processEvent(event) {
  const hubspotClient = new hubspot.Client({ apiKey: process.env.WhiteRabbit });

  let dealId = event.object.objectId;

  hubspotClient.crm.deals.basicApi
    .getById(dealId, ['test'])
    .then(results => {
let dateString = results.body.properties['test'];
let newDate = addMonths(dateString,12);
console.log(newDate); 
  
    hubspotClient.crm.deals.basicApi
        .update(
          dealId,
          {
            properties: {
              ['test']: addMonths(dateString, 12)
}
          }
        )
    });
}
function addMonths(date, months) {
	var od = new Date(date);
	var nd = new Date(date);    
	var od_m = od.getMonth();
    od.setMonth(od_m + months);
		if (od.getDate() != nd.getDate()) {
      od.setDate(0);
    }
    return od;
}

 

View solution in original post

0 Upvotes
KyleJepson
Inbound Professor

I've been working on a similar project (I made a separate thread about that), and it taught me a lot about dates in Javascript and HubSpot. (Like you, I'm learning Javascript on the fly, here.) I still don't know enough to troubleshoot your code, but I was able to write this code that gets the job done:

 

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

exports.main = (event, callback) => {
  callback(processEvent(event));
}

function processEvent(event) {
  const hubspotClient = new hubspot.Client({
    apiKey: process.env.WhiteRabbit
  });
  
  let dealId = event.object.objectId;
  hubspotClient.crm.deals.basicApi.getById(dealId, ["test"])
    .then(results => {
      let dateString = new Date(results.body.properties.test);
    
dateString.setFullYear(dateString.getFullYear() + 1);
    
    hubspotClient.crm.deals.basicApi.update(
      dealId,
      {properties: {["test"]: dateString}}
    )
    
    })
}

 

The top part is the same as yours. The important part is this bit in the middle: dateString.setFullYear(dateString.getFullYear() + 1);

 

dateString.getFullYear() returns the year from dateString. dateString.setFullYear() updates the year of dateString. So I put getFullYear() + 1 inside of setFullYear(), and that did the trick.

 

Does that help?

 

 

0 Upvotes