Working with a timezone offset in Suitescript 2.x

Few things exist in life for which you would find more developer consensus than saying that working with dates in Javascript is terrible. We are in 2023 now and this has not changed at all.

Most of the time, these issues revolve around dealing with timezones and offsets, as in: The client is sending the date as a string, you parse that into a Date object in the server but the server uses a different timezone an it substracts the hours based on the timezone difference, often resulting in the server storing a different date altogether (specially if you are working after midnight).

(I do apologize if this is triggering any kind of Javascript PTSD)

Sure, there are modules whose only purpose in life is to aid in these endeavors, such as MomentJS and DayJS (My personal favorite), however, there are times and environments in which inserting an external Javascript module is either too hard or an overkill and a native solution is preferable (or required).

About my specific situation:

  • From the client application I was sending a date string, formatted as: “2023-01-06”
  • The server took this string (Via Restlet context) and when I used new Date(date) the server parsed it to the previous date (Jan 5).

The solution, while arguably ugly, solved my problem without additional dependencies, it works as follows:

let date_raw = new Date("2023-01-06");

let date = new Date(date_raw.getTime() + (date_raw.getTimezoneOffset() * 60 * 1000));

Where:

  • date_raw.getTime() returns the number of miliseconds since the unix epoch time (The beginning of time as far as the computer is aware of) until the specific date.
  • (date_raw.getTimezoneOffset() * 60 * 1000)) returns the difference in minutes between the original date in UTC timezone and the equivalent date in the server’s timezone. Then it turns it into miliseconds so that the resulting value is compatible with the previous parameter.
  • We add these two values and end up with a date object for which the timezone offset for the server’s timezone is already added.

Passing this resulting date object to a record using record.setValue({fieldId: 'datefield', value: date}); resulted in the proper date being persisted in Netsuite’s database (and me being able to call it a day and go to sleep).

Relevant Insights

Recent Case Studies