function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jeremiahnelsonjeremiahnelson 

Setting a date field to today using an on-click javascript custom button.

Hi all -


I'm struggling with how to set a date field to today() using a custom button's on click javascript.

 

I'm using the button to set the value of two picklist values, set a date field to Today() and set a second date field to Today()+180.

 

When I first wrote it and tested it earlier in the week, it was executing but was setting the wrong dates. Today it just errors out.

 

 

{!requireScript("/soap/ajax/13.0/connection.js")} var QR= new sforce.SObject("Quote_Request__c"); QR.id = "{!Quote_Request__c.Id}"; var temp_dev_date=new Date(); temp_dev_date.setDate({!TODAY()}) var temp_val_date=new Date(); temp_val_date.setDate({!TODAY()}+180) QR.Delivered_Date__c=temp_dev_date; QR.Validity_Date__c=temp_val_date; QR.Customer_Requirements__c="Test update of auto close button."; QR.Status__c="Closed - Completed"; QR.Stage__c="Delivered"; var result = sforce.connection.update([QR]); if (result[0].getBoolean("success")) { // Refresh window window.location.reload(); } else { alert("something broke"); }

 

Appreciate any guidance or other approaches that could be used to accomplish this.

RupBRupB

Hi Jeremiah,

 

I tried with NOW () :

 

opp.CloseDate = "{!NOW()}";

produces

Failed to create 'New Opportunity' with error: {faultcode:'soapenv:Client', faultstring:''01/07/2009 15:04' is not a valid value for the type xsd:date', }

I support you : "What's the solution ?"   !!!
Rup

 

SunilSunil

You can use: -

 

opp.CloseDate = New Date();

 

This will set current date to CloseDate.

Chief__cChief__c

I was trying to solve the same problem today, your code provided a good start for me. I ended up writing the following functions:

 

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.getYear() + "-" + Month + "-" + Day + "T" + Time; 
}

 

The date object that javascript uses has a different format than the one used by Salesforce. These functions convert the format.

 

QR.Delivered_Date__c= fixDate(new Date());

 

 

Message Edited by Chief__c on 07-08-2009 02:08 PM
RupBRupB

Here is my own solution :

 

 

function right(str, len) { return str.substring(str.length-len, str.length) } function mynow() { d = new Date(); return right("00"+d.getFullYear(), 4) + "-" + right("00"+(1+d.getMonth()), 2) + "-" + right("00"+d.getDate(), 2); // format "2009-007-02" }

 

 Call this like this :

 

opp.CloseDate= mynow();

 

 

 

 

jeremiahnelsonjeremiahnelson
RupB - i've seen this solution on the web and it works well for today's date, but the problem for me is how do I also set the other date to today()+180..
Ron WildRon Wild

I think Salesforce requires the full four-digit year ... might want to use date.getFullYear() instead of date.getYear() as shown below.

 

 

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; }

 

 

 

CloudLearnerCloudLearner

Hi RupB,

 

I ran into the same error, did you get the resolution for this?

 

Thanks in anticipation

PFangPFang

Hi,

 

I checked out your JAVA fix and noticed that it may just be the solution to this brickwall I ran into. I have the following custom button OnClick Javascript code on a sample object that should imprint both Date and Time values on a DateTime field. I did use the new Date() syntax but it only works for Date fields and not DateTime. I was wondering, how your post would fit into what I've formulated. Thanks in advance!

 

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 
var v=new sforce.SObject("Opportunity"); 
v.JavaDateButtonTest__c="{!Opportunity.JavaDateButtonTest__c}"; 
v.id = "{!Opportunity.Id}"; 
if((v.JavaDateButtonTest__c=='')) 

var date = new Date('{!TODAY()}'); 
v.JavaDateButtonTest__c=date; 
result=sforce.connection.update([v]); 
}

 

-----------------------------------------------------------

 

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; 
}

 -----------------------------

 

I also got this from another site and I'm not sure if this is usable for what I cited above:

 

http://www.ladysign-apps.com/blog/code/salesforce/salesforce-datetime-functions/comment-page-1/#comment-483

 

/**
* Set Javascript Date Time to Salesforce Date Time;
* @param dateTimeObj - date time string
* @return salesforce date time object
**/
function setStringToDateTime(dateTimeObj){
    var dateTimeObj;
 
    if (dateTimeObj != null) {
        dateTimeObj = sforce.internal.stringToDateTime(dateTimeObj);
    }
 
    return dateTimeObj;
}

 

Mark JaundooMark Jaundoo
Any resolution to this?
Jasleen MakkarJasleen Makkar
This code worked for me!!

var today = new Date();

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;
}

postObj.Accept_Time__c = fixDate(today);
Joy JeyakumarJoy Jeyakumar
The below code worked for me for a field of type Date

The below code snipper considers the field Closed Date is of type Date in an object named Sample

var dt = "{!DAY(TODAY())}";
if (dt < 10){dt = "0"+ dt;}
var mon = "{!MONTH(TODAY())}";
if (mon < 10){mon = "0"+ mon;}

var samp = new sforce.SObject("Sample__c");
samp.ClosedDate__c = "{!YEAR(TODAY())}-"+mon+"-"+dt;
lavanya k 8lavanya k 8
Hi Joy,
Thank you , It helped me.
Kuljot VijKuljot Vij

Hi,

You could try below:

1. If today's date

opp.CloseDate = {!Today}
 

2. If today's + some days
 

var start = new Date;

opp.CloseDate = new Date(start.setDate(start.getDate() + 30));

Thanks!

Meghna BhargavaMeghna Bhargava
Hi jeremiahnelson

Here I have used now() instead of today() for On-click Javascript button. This will fetch you datetime:
In this, IT_Tracking__c is my custom object. You can replace it with your object.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var track = new sforce.SObject('IT_Tracking__c');
track.id = "{!IT_Tracking__c.Id}";
var startDate = "{!NOW()}";
var sDate = new Date(startDate); 
var startDate = sDate.toISOString(); 
track.start__c = startDate;
var result = sforce.connection.update([track]);
if (result[0].success == 'false') {
alert(result[0].errors.message);
}
else {
location.reload(true);
Richard Houston GMURichard Houston GMU
I just want to call to attention to a new Javascript function that Meghna used here to solve the problem.

The toISOString() function changes the javascript date/time to the format that Saleforce can consume. Here is the documentation on the function (https://www.w3schools.com/jsref/jsref_toisostring.asp). 

Using that will save anyone the need to create the separeate functions to transform the data. 
Jamil Vallis-WalkerJamil Vallis-Walker
Hi all,

I know this is an old post, but I thought I would share my solution all the same. the "DATE_FIELD_ID_HERE" is a placeholder for whatever yoru date field ID is (might seem obvious, but I'm a fan of clarify).
 
{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

var year = {!YEAR( Today() )};
var month = {!MONTH( Today() )};
var day = {!DAY( Today() )};

var today = month + "/" + day + "/" + year;

var link = "https://cs70.salesforce.com/a2H/e?DATE_FIELD_ID_HERE=" + today

window.location.href= link;