Home > database >  Google Sheet App Script to toLocaleString returning M01 not January
Google Sheet App Script to toLocaleString returning M01 not January

Time:10-29

I have the following app script being called from a cell and I expected the result to be January but M01 is coming back. This general logic is used elsewhere fine so not quite sure what I'm doing wrong. The getFullYear is working fine.

Thanks in advance for your help.

function actualBudget(date) {
 const dateObj = new Date(date)
 const month = dateObj.toLocaleString('default', { month: 'long' })
 const year = dateObj.getFullYear().toString()
 return month
}

enter image description here

CodePudding user response:

I have experienced the same issue with you. At that time, the reason for the issue was the locale value. So, I thought that when I saw your script, default locale might be the reason for your issue. So for example, how about modifying from default to en-US as follows?

From:

const month = dateObj.toLocaleString('default', { month: 'long' })

To:

const month = dateObj.toLocaleString("en-US", { month: 'long' });
  • In this case, please modify en-US for the locale you want to use.

Note:

  • When the custom function is not used, Session.getActiveUserLocale().replace("_", "-") can be used. But in the case of the custom function, Session.getActiveUserLocale() returns the empty value. Because the script is not run by the active user. By this, I proposed to manually set the locale.

Reference:

  • Related