On a RESTlet response, we're getting an invalid da...
# suitescript
k
On a RESTlet response, we're getting an invalid date value (must be M/D/YYYY) error. Am I correctly setting the string to a data object?
Copy code
// From "2021-08-19T00:00:00"
function convertStringToObj(timeString) {
    if (timeString !== null && timeString !== "") {
      var dateString =
        timeString.substring(5, 7) +
        "/" +
        timeString.substring(8, 10) +
        "/" +
        timeString.substring(0, 4);
      var d = new Date(dateString);
      return d;   //Expecting 08/19/2021
    }
    return "";
  }
w
new Date()
does not output a string. d would be a Date-object
k
I'm using setValue to pass the date object into a record.
Would that be the ideal approach?
w
new Date(timeString.substring(0,10)) should be enough to convert your values to a date object
Are you sure you're getting a date-object from that function as it is now?
k
Not sure.
a
he's absolutely not getting a date object value for d from the current function, it will return a string.
k
@Anthony OConnor, could you clarify?
a
the function that you have currently is returning a string
"08/19/2021"
NS is expecting a js date object, not a string when setting a value for a date field (since SS 2.0)
that's what Watz was saying, you need to use
new Date()
to get a date object
dont need to parse each number... you can grab the first 10 characters and just pass that to new Date()
w
In the browser, new Date() accepts a date-string in the format that the funktion concatenates. But it might be different in NS
a
message has been deleted
Copy code
function convertStringToObj(timeString) {
    if (timeString !== null && timeString !== "") {
      return new Date(timeString.substring(0,10))
    }
    return "";
  }
oh wow, I'm dumb, I didn't even see you were already doing a new Date in your function, i thought you were just returning the string... ok now I have no idea
k
Lol no worries.
w
I'd do as Anthony wrote. But it appears to work in the browser
You might need to check what is happening with the date object where you use it. How do you use setValue?
k
Copy code
recordLine.setValue(Obj.obj[fldMilestoneName], convertStringToObj(obj["obj"][fldMilestoneName]));
a
umm
Obj.obj
vs.
obj["obj"]
k
Obj.obj is an object record. obj["obj"] is API payload
Copy code
{
"shipments": [
   {
     "milestones: {
        "field": "2022-12-06T00:00:00Z"
     }
   }
 ]
}
w
Consider using providing an object for the setValue function for clarity.
Run the date function before the setValue and log the values
What is recordLine? Sounds like it is a sublist line on a record
a
umm shouldn't setValue be in the form
Copy code
recordLine.setValue({ fieldId: Obj.obj[fldMilestoneName],
                      value: convertStringToObj(obj["obj"][fldMilstonename])
                    });
or are you using SuiteScript 1.0?
k
2.1
a
pretty sure all 2.x NS apis are in the form of module.method({params});
k
recordLine is sublist
a
sorry I have a meeting, if this is still not resolved in ~30 mins I'll get back into it 😄
🙌 1
w
If obj[“obj”] is what you wrote. Shouldn't you address the date value with obj[“obj”][fldMilestonename][0].milestones.field?
k
The value is able to update, but I'm not sure why the error is still occurring.
w
You don't use setValue on a sublist
k
Watz, I apologize, but I found it's not a sublist.
w
Either setSublistValue or setCurrentSublistValue
k
It's a custom record with no sublist
a
is the data type of the custom field you're targeting a date field?
obv. if its free form text, and you're passing a date obj its gonna complain 🙂
k
Field types are set as Date.
w
Copy code
var dateObj = convertStringToObj(obj["obj"][fldMilstonename])
log.debug(“check”,{value: dateObj, typeOf: typeof dateObj})
run this before your set value and verify that you get what you expect. Also change setValue to specify the parameters.
a
ok and they're just custom fields, not sublist fields on a custom record?
k
Correct
a
ok and so
recordLine
is actually a custom record object reference?
this is what a
setValue
needs to look like
w
They are overloaded, so sometimes you don't need to. But I'd opt for using an object.
a
the error is complaining about wanting a specific date format, and that's the error I would expect from passing a js date obj to a date field using SS 1.0 that's why I'm recommending using the official 2.0 syntax 😉
w
SS1.0 functions aren't available in SS2.x server scripts afaik
b
the error about the date format is deceptive
setValue uses a Date as a value to set date related fields
but internally it converts it to a string in the current user's format
if you are getting that error, it means that the conversion failed
so you should really be checking if you are getting a valid Date out of your function
k
I realized that NS is accepting the date value, but the error occurs on the API response.
I was able to revert to the backup code and find the issue. Thanks everyone for your help!
🙌 1
z
Copy code
const sefToUTCDateString = (tmpUtc) => {

            //  01234567890123456789012----
            // "2022-07-12T11:44:28.6089274+00:00"

            const year = parseInt(tmpUtc.substring(0, 4));
            const month = parseInt(tmpUtc.substring(5, 7)) - 1;
            const day = parseInt(tmpUtc.substring(8, 10));
            const hour = parseInt(tmpUtc.substring(11, 13));
            const minute = parseInt(tmpUtc.substring(14, 16));
            const seconds = parseInt(tmpUtc.substring(17, 19));

            const tmpDate = new Date(year,month,day);

            const sDate = format.format({
                value: tmpDate,
                type: format.Type.DATE
            }); // formated as User Date Format, but only dd.mm.yyyy

            const sDateTime = sDate + ' ' + hour + ":" + minute + ":" + seconds;

            return (format.parse({
                value: sDateTime,
                type: format.Type.DATETIME,
                timezone: format.Timezone.GMT
            }));
        }
I spent whole yesterday to fight with date type in NetSuite …. And I found a hundreds post about it and always stay confused
You should care about • new Date() return time from server! not from user • there is difference in dateformat string (dd.mm.yyyy, MM/DD/YYYY …….) and it is related to LOGGED USER date format • and one million other traps :(
and now I have similar question how-to • I need set a variable to TODAY but specific timezone (UTC+2) • it is used in scheduled script, there is no USER logged in (scheduler) • it is set up to run at 06:00 (timezone UTC+2) and I need date value for YESTERDAY in local timezone, not in server timezone (PACIFIC)
b
honestly most attempts to use format and parse on the same input are flawed
the code you have assumes the user's time format is the 24 hour one using colons instead of hyphens
its also overkill, the 2.1 new Date constructor is able to recognize more forms of iso-8601 than the 2.0 one
Copy code
new Date("2022-07-12T11:44:28.6089274+00:00")
should get you the correct date, minus the nanoseconds
z
it will be in which timezone? if used in M/R script
b
working with Date means understanding that
Copy code
new Date("2022-07-12T11:44:28.6089274+00:00")
and
Copy code
new Date("2022-07-12T13:44:28.6089274+02:00")
are the same Date
they both represent the same moment in time, its just displayed differently
all that timezone stuff is getting a nicer display value
you will generally also want to get way more specific about what you mean by today, as far as javascript is concerned, there are 86,400,000 Dates representing today
z
Copy code
tmpDateTime = new Date("2022-07-12T11:44:28.6089274+00:00")

sefPurchaseRecord.setValue({
                    fieldId: 'custrecord_rdata_sef_pi_lastmodified', // DATETIME field type
                    value: tmpDateTime
                });

Above code is running in M/R 
So your final instruction is to use +00:00 to set GMT / UTC zone if I know that)\
and I ask for the last trick I wrote above > I have external REST server, in different timezone than NetSuite. I need to create REST call with date, relative to TODAY but today meaning to REST server. new Date() in NetSuite will generate date object with “today” in NetSuite timezone. Any trick? Just to use new Date() and then add 9hours? it is difference between NS and REST server I call
b
the current code you shared will set that datetime field to a date representing "2022-07-12T114428.000000+00:00", you lose the milliseconds
you will want to confirm that yourself by looking at the record via a user using different timezones
a user on gmt casablance is easiest since they will be using the same timezone as the string you are using
but you will probably want to see the behavior when you switch timezones
z
@battk>you lose the milliseconds … Yes I know, I dont need miliseconds, neihter seconds ..
b
you still arent properly defining what you mean by today
if you mean now, then now on the external rest server is the same date as now on the netsuite server
minus whatever differences in actual clock between the two systems
z
Ok lets simplified, I am not talking about now on the server level • let`s say in the Europe is Thu 19 Jan, 6am (UTC+2) • scheduled script is set to run at every day on 6am (UTC+2) • I need to calculate start and end date, in my case 17-18 Jan without time. REST Server request format YYYY-MM-DD, no time • If I used in scheduled script sDate = new Date() … it will return Wed 18 9pm ( 9 hours difference ) • calculation sDate.setDate(sDate() - 2) returns 16 That is result in my Scheduled script
Am I confused?
translate to human word > I am asking NetSuite server what date is NOW at this moment in Germany … it can be different (9 hours difference)
BTW, @battk thank you very much for your patience with me 🙂
b
not really good enough
jan 17-18 for me means something different to jan 17-18 on your server
same thing for jan 17-18 for you
for each of us those are different 24 hour ranges, with varying levels of overlap
the thing, you are also asking about now, which is distinct from those different ranges
as i said before, now is the same Date for all 3 of us, its just that we express it as different strings
javascript Date's dont care about those differences in strings
so before you try to go much futher do you understand why
Copy code
new Date("2022-07-12T11:44:28.6089274+00:00")
and
Copy code
new Date("2022-07-12T13:44:28.6089274+02:00")
reprresent the same Date
z
Of Course … I know +02:00 means that datetime STRING is UTC+2 …. with Z or +hh:mm you are “saying” to Date constructor what timezone is…. returned value is the same … So, there is no question how to convert string into DateTime … Let’s try to explain my problem • I have a Scheduled script running every 1 hour. • The client need to send GET request to external server (Germany time zone) with parameter YYYY-MM-DD. That date MUST BE PREVIOUS day relative to date in Germany. At this moment it is 2023-01-18 • An variable is created > let tmpDateTime = new Date() Ok, I assume that we now have a UTC/GMT date & time … Question is > what is date and time in Germany, Romania, Tokyo … any other timezone? THIS >>> format.format(…format.Timezone.ASIA_TOKYO) ? tmpDateTime.getDay() will return what? UTC day ?
toString() …. convert into PST timezone …
b
relative to germany means you want to use moment timezone, which allows you to use different timezones on your dates, it will allow you to manipulate and display the date relative to germany timezone
you can mostly get it working without moment timezone if you allow yourself to be wrong on daylight savings by just adding hours to the date
its essentially guaranteed that getting moment timezone to work will be easier than trying to manipulate the Date yourself
z
Thx...