Saturday, March 30, 2019

Retrieve Time from Date/Time Field type based on Date and Time format

Question:

User wants to retrieve Time from Field type Date/Time based on Date and Time format set in User Preferences.

Answer:

Best way is to use native Javascript function Split().For loading Date and Time formats is used nlapiLoadConfiguration API.
This API is available in scheduled scripts, user event scripts, and Suitelets.


Here is an Example of User Event script Before submit function:


function userEventBeforeSubmit(type){

// load the user preferences page
var userPreferences = nlapiLoadConfiguration('userpreferences');

// get time and date format
var dateFormat = userPreferences.getFieldValue('dateformat');
var timeFormat = userPreferences.getFieldValue('timeformat');

// put ID of your date/time field here
var dateTimeString = nlapiGetFieldValue('date-time-field-id');

// string from date/time field splitted by spaces into array
var dateTimeArray = dateTimeString.split(" ");
var time = "";

// if there are no spaces in date, start at position 1 (second one), otherwise start at position 3 (2 spaces)
var itemToStart = "1";
if (dateFormat == "DD MONTH, YYYY"){
 var itemToStart = "3";
}

// set split char according to set time format
var splitChar = ":";
if ((timeFormat == "fmHH24-fmMI") || (timeFormat == "fmHH-fmMI am")){
 var splitChar = "-";
}

// go thru time part of date/time field
for(var i = itemToStart; i < dateTimeArray.length; i++){
 time = time + " " + dateTimeArray[i];

 // remove seconds using split char
 if (i == itemToStart){
  var timeArray = dateTimeArray[itemToStart].split(splitChar);
  time = timeArray[0] + splitChar + timeArray[1];
 }
}

// put ID of your time field here
nlapiSetFieldValue('time-field-id',time);
}


No comments:

Post a Comment