[SalesForce] javascript date on custom button issue..

When i click on this custom button i need to fill a field with the current date and time.But some times its giving me a previous date i.e exactly 1 day prior to current date..i dont know why this is happpening..can some help me out in this..may be there is some issue with javascript…or timezone issue..as its not happening everytime…but sometime..

var SO = new sforce.SObject("Sales_Order__c");

    function fixTime(time){
       if(time < 10) {time = "0" + time};
       return time;
    }
     function fixDate(date){
      var Month = fixTime(date.getMonth() + 1);
      var Day = fixTime(date.getDate());
      var UTC = date.toUTCString();
      var Time = UTC.substring(UTC.indexOf(':')-2, UTC.indexOf(':')+6);
      var Minutes = fixTime(date.getMinutes());
      var Seconds = fixTime(date.getSeconds());
      return date.getFullYear() + "-" + Month + "-" + Day + "T" + Time;  
    }

    SO.date__c = fixDate(new Date());
updateSO = sforce.connection.update([SO]);

Best Answer

You're getting the local time zone year, month and day, but UTC time hours and minutes. When it's today here and tomorrow in UTC, your date calculations will become a day behind. Example follows:

Local time: 2013-12-31 22:00 -05:00
UTC time: 2014-01-01 03:00 -00:00

Year = 2013
Month = 12
Day = 31
Time = 03:00

So, you're committing the value of '2013-12-31T03:00Z' instead of '2014-01-01T03:00Z'.

There is no need for any of this code at all. The function sforce.internal.dateTimeToString automatically converts the date/time coordinate to the correct value for you as long as it is a native Date object.

In other words, change your code to:

var SO = new sforce.SObject("Sales_Order__c");
SO.Date__c = new Date();
SO.Id = "{!Sales_Order__c.Id}";
updateSO = sforce.connection.update([SO]);

Do not call sforce.internal.dateTimeToString, as it is already called for you, and as the "internal" suggests, you should not be using that function explicitly.

Edit You need to include the ID value to update a record. This is most likely the problem.

Related Topic