Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a date to a string - SuiteScript 2.0

Goal: Convert JS Date Object to a String representation in the format of "11/2/2017" in a NetSuite SuiteScript 2.0 scheduled script.

I have a date object that I need to use for 2 purposes. In one, I am going to use it for comparisons (so I want the actual date object). The other is I want it to be the name of a Custom Record, ie a string value.

I am doing this in NetSuite SuiteScript 2.0 (Javascript) in a Scheduled Script. The toString() of the date right now is: "2017-11-02T07:00:00.000Z". The format I want to end up with for the name is 11/2/2017.

When I test toLocaleDateString() in a browser test app, I get 11/2/2017 - the exact format I want. However, when I sue this same thing in SuiteScript 2.0 I get "November 2, 2017". I know there is a difference between client/server but this was frustrating.

I tried the format.parse() function as NetSuite's documentation claims that this is the equivalent to the 1.0 nlapiDateToString() function. This did not work.

Besides writing my own function (which I am tempted to do), does anyone know how to accomplish this goal?

like image 467
TMann Avatar asked Dec 14 '22 20:12

TMann


2 Answers

To switch over to that format you would not use format.parse, you would use format.format. Here is a simple example of converting a date object to that string format.

require(['N/format'],function(format){
  function formatDate(testDate){
    log.debug('testDate: '+testDate);
    var responseDate=format.format({value:testDate,type:format.Type.DATE});
    log.debug('responseDate: '+responseDate);
  }

  var testDate=new Date();
  formatDate(testDate);
});
like image 65
w3bguy Avatar answered Feb 03 '23 01:02

w3bguy


I'm going to suggest using the momentJS library for all of your SuiteScript date manipulation needs. It works well as a SuiteScript 2.0 module and you can format dates easily:

var now = new Date();
var formattedDate = moment(now).format('M/D/YYYY');
like image 33
Mike Robbins Avatar answered Feb 03 '23 01:02

Mike Robbins