Reputation: 1022
I have a function in my library to return the current date:
function currentDate(addDays) {
if (addDays == null||addDays == undefined) {
addDays = 0;
}
var currentdate = new Date();
var current = nlapiAddDays(currentdate,addDays);
var day = current.getDate();
var month = current.getMonth()+1
var year = current.getFullYear();
return day+'/'+month+'/'+year;
}
All works fine, until I run a scheduled script which utilises this function, at which point the date returned is UTC, not our local time. Is there a simplistic method of conversion within this function without the need for external libraries?
Upvotes: 1
Views: 2850
Reputation: 3029
Suitescript 2.0 version of @lez-yeoh getCompanyDate
function getCompanyDate(){
var currentDateTime = new Date();
var companyTimeZone = config.load({ type: config.Type.COMPANY_INFORMATION }).getText({ fieldId: 'timezone' });
var timeZoneOffSet = (companyTimeZone.indexOf('(GMT)') == 0) ? 0 : Number(companyTimeZone.substr(4, 6).replace(/\+|:00/gi, '').replace(/:30/gi, '.5'));
var UTC = currentDateTime.getTime() + (currentDateTime.getTimezoneOffset() * 60000);
var companyDateTime = UTC + (timeZoneOffSet * 60 * 60 * 1000);
return new Date(companyDateTime);
}
Upvotes: 2
Reputation: 2840
This is what I do but you consume usage units since you have to create record.
First I create a hidden custom Date/Time field. Then I use the following code.
var record = nlapiCreateRecord(<recordtype>);
record.setDateTimeValue(<fieldid>, nlapiDateToString(new Date(), 'datetimetz', 5);
var userDateTime = record.getFieldValue(<fieldid>);
The variable userDateTime should now be in the local time zone.
The nlapiSetDateTimeValue() API function will convert the date/time value to the user's timezone. Below is its syntax:
nlapiSetDateTimeValue(fieldId, dateTime, timeZone)
Upvotes: 0
Reputation: 350
Here is a utils function that I've used for years.
function getCompanyDate(){
var currentDateTime = new Date();
var companyTimeZone = nlapiLoadConfiguration('companyinformation').getFieldText('timezone');
var timeZoneOffSet = (companyTimeZone.indexOf('(GMT)') == 0) ? 0 : new Number(companyTimeZone.substr(4, 6).replace(/\+|:00/gi, '').replace(/:30/gi, '.5'));
var UTC = currentDateTime.getTime() + (currentDateTime.getTimezoneOffset() * 60000);
var companyDateTime = UTC + (timeZoneOffSet * 60 * 60 * 1000);
return new Date(companyDateTime);
}
It uses your company's NetSuite settings and timezone. This will return the date in the correct timezone assuming your NetSuite settings are correct.
You could then essentially do:
function currentDate(addDays) {
if (addDays == null||addDays == undefined) {
addDays = 0;
}
var currentdate = getCompanyDate();
var current = nlapiAddDays(currentdate,addDays);
var day = current.getDate();
var month = current.getMonth()+1
var year = current.getFullYear();
return day+'/'+month+'/'+year;
}
Upvotes: 4