CRM 2011 Timezone in OnChange Event - javascript

I'm in the process of customizing our CRM solution. Due to different timezone, sometimes due dates in Cases or Tasks are not consistent because the time defaults to midnight 12 am. So to different timezone the due date could be one day later or earlier.
In order to fix this we're setting the default time of the due date field (logical name = "followupby" ) to 7 PM. We're creating an OnChange event for the Due date field with Java script function as follow. In "Handler Properties" dialogue to set up the Library and Function name, I check the option to "Pass execution context as first parameter". Therefore in my function below it's receiving the 'context' parameter:
setCaseDueDate: function (context) {
var oField = context.getEventSource().getValue();
var sTmp = oField;
var hours =19;
var minutes = 0;
var seconds = 0;
if (typeof (oField) != "undefined" && oField != null) {
var newTime = new Date(sTmp.getFullYear(), sTmp.getMonth(), sTmp.getDate(), hours, minutes, seconds);
context.getEventSource().setValue(newTime);
}
},
However I keep getting an error that says "There was an error with this field's customized event. Error 'setCaseDueDate' is undefined."
Could it be that certain values in my function is undefined or is it probably not getting the 'context' parameter correctly?
Thanks, greatly appreciate your help.
***UPDATE**********
Nevermind this... I was putting my function with existing collection of Javascript functions and then I decided to put into a separate new webresource and it's working now... weird but works.
Thanks.

Your code to define a JavaScript function is wrong, try with
function setCaseDueDate(context) {
// rest of the code
}
and to change the date, it's not necessary the context, for example:
function setCaseDueDate() {
var fieldName = "followupby";
var sTmp = Xrm.Page.getAttribute(fieldName).getValue();
if (currentDate != null) {
var newTime = new Date(sTmp.getFullYear(), sTmp.getMonth(), sTmp.getDate(), 19, 0, 0);
Xrm.Page.getAttribute(fieldName).setValue(newTime);
}
}

Related

Adding time (sec and min) to a js var

i've a question: in a JS file i have a variable (returned from an ajax call) that contains a time formatted in hh:mm:ss.
My question is: how can i add X minutes and X seconds to that time?
i tried in this mode:
var lastop = moment(data['lastOp']); //10:04:00
var summa = lastop.add(data['sessionLease'],'minutes');
But in consolle i receive this:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Arguments: [object Object]
Error
at Function.createFromInputFallback
How can i solve my problem?
Many thanks
Use moment with a format string, as the issue that error message pointed you to told you to:
var lastop = moment(data['lastOp'], "HH:mm:ss");
...then add the minute and second:
lastop.add(1, "minute");
lastop.add(1, "second");
Example:
var data = {
lastOp: "10:04:00"
};
var lastop = moment(data['lastOp'], "HH:mm:ss");
lastop.add(1, "minute");
lastop.add(1, "second");
console.log(lastop.format("HH:mm:ss"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
It works perfctly!
Now i need to subtract actual time to a time variable (formatted in hh:mm:ss), for ex:
var time1 = 13:40:00
var time 2 = time1 - now time // How can i do?

Google Form on Submit get values and format the time

I am using Google Apps Script with a Google form. When the user submits the Google Form I get a value from a question. I then take that value and make it a date object, from what I saw on this post about daylight savings I use that to determine the timezone. I run the date object through Utilities.formatDate and want to get the correctly formatted date.
example: 9:00 AM
But instead I am getting a completely different time than expected.
My question is: Can someone help me understand why the below code is outputting a time that is 3 hours different?
function onSubmit(e) {
var values = e.values;
Logger.log(values);
try {
var start1 = new Date(values[3]);
var startN = new Date(start1).toString().substr(25,6)+"00";
var startT = Utilities.formatDate(start1, startN, "h:mm a");
Logger.log(startT);
} catch(error) {
Logger.log(error);
}
}
The assumption that Utilities formatDate does not support GMT... parameter is not true.
The post you mentioned in reference is used to get calendar events and is a useful way to get the right value when you get events from another daylight saving period (getting the TZ info from the calendar event itself), for example events for next month will be in "summer time" while we are still in "winter time"...
Your issue might come from different sources depending on time zone settings of your script vs timezone of the source. Could you describe the exact configuration in which you use this script ?
In the mean time, here is a small code that demonstrates how the code is working + the logger results :
function testOnSubmit() {
var eventInfo = {};
var values = {};
values['3'] = new Date();
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n\n');
onSubmit(eventInfo);
}
function onSubmit(e) {
var values = e.values;
try {
var start1 = new Date(values[3]);
Logger.log('onSubmit log results : \n');
Logger.log('start1 = '+start1)
var startN = new Date(start1).toString().substr(25,6)+"00";
Logger.log('startN = '+startN);
var startT = Utilities.formatDate(start1, startN, "h:mm a");
Logger.log('result in timeZone = '+startT);
} catch(error) {
Logger.log(error);
}
}
EDIT : additionally, about the 30 and 45' offset, this can easily be solved by changing the substring length like this :
var startN = new Date(start1).toString().substr(25,8);
the result is the same, I had to use the other version a couple of years ago because Google changed the Utilities.formatDate method at some moment (issue 2204) but this has been fixed.
EDIT 2 : on the same subject, both methods actually return the same result, the GMT string has only the advantage that you don't have to know the exact timezone name... there is also the Session.getScriptTimeZone() method. Below is a demo script that shows the resulst for 2 dates in January and July along with the log results :
function testOnSubmit() {
var eventInfo = {};
var values = {};
values['3'] = new Date(2014,0,1,8,0,0,0);
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n\n');
onSubmit(eventInfo);
values['3'] = new Date(2014,6,1,8,0,0,0);
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n');
onSubmit(eventInfo);
}
function onSubmit(e) {
var values = e.values;
var start1 = new Date(values[3]);
Logger.log('onSubmit log results : ');
Logger.log('start1 = '+start1)
var startN = new Date(start1).toString().substr(25,8);
Logger.log('startN = '+startN);
Logger.log('result in timeZone using GMT string = '+Utilities.formatDate(start1, startN, "MMM,d h:mm a"));
Logger.log('result in timeZone using Joda.org string = '+Utilities.formatDate(start1, 'Europe/Brussels', "MMM,d h:mm a"));
Logger.log('result in timeZone using Session.getScriptTimeZone() = '+Utilities.formatDate(start1, Session.getScriptTimeZone(), "MMM,d h:mm a")+'\n');
}
Note also that the Logger has its own way to show the date object value ! it uses ISO 8601 time format which is UTC value.
Try this instead:
var timeZone = Session.getScriptTimeZone();
var startT = Utilities.formatDate(start1, timeZone, "h:mm a");
The Utilities.formatDate function expects a time zone that is a valid IANA time zone (such as America/Los_Angeles), not a GMT offset like GMT+0700.
I am making the assumption that Session.getScriptTimeZone() returns the appropriate zone. If not, then you might need to hard-code a specific zone, or use a different function to determine it.
Additionally, the +"00" in the script you had was assuming that all time zones use whole-hour offsets. In reality, there are several that have 30-minute or 45-minute offsets.

Monkeypatch the JavasScript date object

I know that this a crazy hack but curious about it anyhow. We have an environment that has the wrong system time and we cannot set it to the correct time. It's specialized hardware so we cannot change the system time. We do however have a service that gives us the correct current time. Our issue is that a bunch of ssl and token signing libraries break because they are getting the wrong datetime from the javascript Date object ( since we have the wrong system time).
What's the way to monkeypatch the Date object's constructor so that we can feed it the correct time to initialize with so that all subsequent calls to Date(), Date.toString(), etc... in the dependent libraries will return our new method that returns the correct non-system time?
Will this work?
var oldDate = Date;
Date = function(){
return new oldDate(specialCallToGetCorrectTime());
}
Date.prototype = oldDate.prototype;
Will this work?
No, since it does not respect arguments given to your new Date function or whether it was called as a constructor vs not. Also you forgot to fix Date.now(). You still will need to get those right:
Date = (function (oldDate, oldnow) {
function Date(year, month, date, hours, minutes, seconds, ms) {
var res, l = arguments.length;
if (l == 0) {
res = new oldDate(Date.now());
} else if (l == 1) {
res = new oldDate(year); // milliseconds since epoch, actually
} else {
res = new oldDate(
year,
month,
l > 2 ? date : 1,
l > 3 ? hours : 0,
l > 4 ? minutes : 0,
l > 5 ? seconds : 0,
l > 6 ? ms : 0)
}
if (this instanceof Date) {
return res;
} else {
return res.toString();
}
}
Date.prototype = oldDate.prototype; // required for instanceof checks
Date.now = function() {
return oldnow() + offset; // however the system time was wrong
};
Date.parse = oldDate.parse;
Date.UTC = oldDate.UTC;
return Date;
})(Date, Date.now);
I just tried this out in the latest Chrome, Firefox, and IE, and it is allowed. I'm not convinced this is better than just fixing the system time (surely it can be fixed), but the approach is doable.
Yes, provided the implementation allows you to redefine window.Date
(It's polite to wrap this sort of thing in a closure)

Make a date/time value called from an API tick very second. (JavaScript)

I'm calling a date and time through an API, which looks like this:
<?php $xml = simplexml_load_file("https://api.eveonline.com/server/ServerStatus.xml.aspx/"); ?>
<div class="server-time">
<?php echo $xml->currentTime; ?>
</div>
This will show a date and time like this on the page:
2013-10-16 08:15:36
Now I want this clock to tick every second and the time and even date (in case it's just seconds before midnight when the user visits the site) values to change accordingly, just like you would expect a digital clock to work.
I know this is possible with JavaScript but since I am a total rookie at it I don't know how to do this - at all.
Help would be highly appriciated!
There are many javascript clocks out there, you don't even have to use an API to get the time and date!
function clock(id) {
//Create a new Date object.
oDate = new Date();
//Get year (4 digits)
var year = oDate.getFullYear();
//Get month (0 - 11) - NOTE this is using indexes, so 0 = January.
var month = oDate.getMonth();
//Get day (1 - 31) - not using indexes.
var day = oDate.getDate();
//Get hours
var hours = oDate.getHours();
//Get minutes
var minutes = oDate.getMinutes();
//Get seconds
var seconds = oDate.getSeconds();
//Maybe create a function that adds leading zero's here
var dateStr = '';
dateStr += year+' - '+month+' - '+day+' '+hours+':'+minutes+':'+seconds;
//Append dateStr to some element.
document.getElementById(id).innerHTML = dateStr;
//Repeat the function every 1000 miliseconds aka 1 second
setTimeout(function() {
clock(id);
}, 1000);
}
The usage would be
<div id="yourID">clock input will go here</div>
clock('yourID');
NOTE
This function has to be called after the DOM is loaded, otherwise this would result in error.
This can be achieved by placing the script tag with your JS at the bottom of the page (not using jQuery that is).
Otherwise if using jQuery, call the $(function() {}) (equivelant to $(document).ready(function() {});
The function is quite self-explanatory, but maybe you would want to read up on the functions to see exactly what they do.
a quick google search should do the trick.
Anyways hope this helps, good luck :)
I'm not sure if you want it to fetch the time from the api every second or, if you want it to just increase every second, starting from the given api time. In the latter case, you should use setInterval:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = $('.server-time').text();
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
$('.server-time').text(date.toString());
}
setInterval(updateTime, 1000);
If you are not using jquery, just use document.getElementById or something like that:
change your element to:
<div id="server-time">
and use the following snippet:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = document.getElementById('server-time').innerHTML;
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
document.getElementById('server-time').innerHTML = date.toString();
}

apps-script: copying a spreadsheet cell to a table, with formatting

I'm writing a script which opens an external Google spreadsheet via a URL. The script needs to copy cells into a FlexTable, and display them.
The problem is that the spreadsheet cells have a custom display format, to show them as elapsed times (m:ss.SS). If I just load up the table element with table.setWidget(x, y, app.createLabel(z)), the label just displays a date in 1899. Any idea how I can copy over the formatting?
Thanks.
EDIT
This nearly does it:
date = new Date(z); // 'z' from 'getValues'
elapsed = Utilities.formatDate(date, "GMT", "m:ss.SS");
table.setWidget(x, y, app.createLabel(elapsed));
Unfortunately, "m:ss.SS"doesn't work; it always displays the milliseconds as 0. Any ideas?
ANOTHER EDIT
apps-script seems to have completely messed this up. This code:
date = new Date();
elapsed = Utilities.formatDate(date, "GMT", "m:ss.SS");
table.setWidget(x, y, app.createLabel(elapsed));
Correctly shows the minutes and seconds portion of the current time, but there are 3 decimal places shown, not 2. This code:
date = new Date(z); // 'z' from 'getValues'
Doesn't work. When z is displayed in the spreadsheet with a non-zero number of milliseconds, this constructor always sets the number of ms to 0 (getMilliseconds returns 0).
Anyone have a work-around? I need apps-script to handle athletics event times, which are generally seconds to 2 decimal places, and possibly a few minutes.
I've noticed that these correspond to dates on December 30, 1899. This is odd - shouldn't this date have a negative time value? The GWT source code for formatDate handles negative values as a special case, and it's difficult to see what it's doing.
There are multiple related and unfixed bugs in this area; see here, for example. It's a bad, bad, idea to let Google sheets handle elapsed times. My eventual solution was to use "integers" to hold the times, and do all the required formatting and processing in GAS (carefully, because they're actually inexact floats, of course). This is pretty easy, and is much better than battling with Date. The only complication is if you need to import Dates from Excel. I had to modify the Excel spreadsheet to convert the dates to ms, and import those instead.
here is a possible workaround to show time the way you want : testsheet (please don't modify)
I used an Ui to define the time value but converted it to a date object in the script to verify how it works with a "real" date object.
EDIT : following the different answers to this post and this other by AdamL, I finally get something that allows displaying and calculating with short time values in hundreds of seconds with help of a UI and custom formatting.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Change cell format", functionName: "EditFormat"},
{name: "Reset format to default", functionName: "ResetFormat"},
{name: "show UI test", functionName: "sportChrono"},
]
ss.addMenu("Custom Format", menuEntries);
}
function EditFormat() {
var oldname = SpreadsheetApp.getActiveRange().getNumberFormat();
var name = Browser.inputBox("Current format (blank = no change):\r\n"+ oldname);
SpreadsheetApp.getActiveRange().setNumberFormat((name=="")?oldname:name);
}
function ResetFormat() {
SpreadsheetApp.getActiveRange().setNumberFormat("0.###############");
}
function sportChrono() {
var app = UiApp.createApplication().setTitle('Show Time in mm:ss.SS');
var main = app.createGrid(3, 4).setWidth('100');
var button = app.createButton('validate')
var btn2 = app.createButton('send to Cell').setId('btn2').setVisible(false)
var time = app.createTextBox().setId('time').setName('time')
var cellist = app.createListBox().addItem('A1').addItem('A2').addItem('A3').addItem('A4').addItem('A5').setVisible(false).setId('cellist').setName('cellist')
var min = app.createTextBox().setName('min');
var sec = app.createTextBox().setName('sec');
var Msec = app.createTextBox().setName('Msec');
main.setText(0,0,'minutes').setText(0,1,'secs').setText(0,2,'millisecs')
main.setWidget(1,0,min).setWidget(1,1,sec).setWidget(1,2,Msec);
main.setWidget(1,3,button).setWidget(2,0,time).setWidget(2,1,cellist).setWidget(2,2,btn2)
var handler = app.createServerHandler('show').addCallbackElement(main)
button.addClickHandler(handler)
var handler2 = app.createServerHandler('writeToSheet').addCallbackElement(main)
btn2.addClickHandler(handler2)
app.add(main)
ss=SpreadsheetApp.getActive()
ss.show(app)
}
function show(e){
var ss=SpreadsheetApp.getActive();
var app = UiApp.getActiveApplication();
var min = e.parameter.min
var sec = e.parameter.sec
var Msec = e.parameter.Msec
var time = new Date()
time.setHours(0,min,sec,Msec)
var nmin = digit(time.getMinutes())
var nsec = digit(time.getSeconds())
var nMsec = digit(time.getMilliseconds())
app.getElementById('time').setText(nmin+':'+nsec+'.'+nMsec)
var btn2 = app.getElementById('btn2').setVisible(true)
var cellist = app.getElementById('cellist').setVisible(true)
return app
}
function writeToSheet(e){
var range = e.parameter.cellist
var val = e.parameter.time
var ss=SpreadsheetApp.getActive();
ss.getRange(range).setFormula('=value("0:'+val+'")');
}
function digit(val){
var str
if(val<10){
str='0'+val}
else if(val>9&&val<99){
str=val.toString()}
else{
str=Math.round(val/10).toString()
}
return str
}

Categories

Resources