Set Default Date/Time Picker Dialog Time

///Set Default Date/Time Picker Dialog Time

Set Default Date/Time Picker Dialog Time

H

ave you ever wondered how you can change the default time displayed in a Date/Time dialog? In general, the Date/Time dialog is controlled by back-end code so there’s not much you can do with it. I’ve seen this question a few times now so I decided to come up with a solution.

Date Time Picker

Because the Date/Time picker dialog is controlled by back-end code, the only way to change the default time is via client scripting. What I found is that you can run a client script when the dialog comes up and set the hours, minutes, and seconds to whatever you want. The trick is running your client script at the right time. You can’t react to a change or a form submission like you might for regular client scripting scenarios. Instead, you need to react to the click of the calendar icon next to the Date/Time field.

Fortunately, the Prototype library that ships with ServiceNow includes something that does exactly what we need…the Event.observe method. The basic idea behind this method is to wait for a specific event (in this case the ‘onClick’ event from the calendar icon) and then run some code along with that event. I’ve used this method before in an article I wrote about controlling the ordering of client-side code.

Event.observe works by attaching itself to a specific event on a specific element. For the purposes of this solution, we need to find the ‘A’ tag associated with the calendar icon (the element) and check for the ‘click’ event. Then we can run the code to set the time to whatever we want…typically midnight or something similar. Below is a function that does just that. It works for regular forms and for catalog items. You just need to call the function and pass in the name of the Date/Time field or variable like this…

setDatePickerTime('<FIELD_OR_VAR_NAME>');

…and here’s the ‘setDatePickerTime’ function

function setDatePickerTime(field){
   //Attach an event listener to set default time value for date picker
   Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
      setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
   });
}

Here’s an example client script I set up on the Incident form to run onLoad (which will almost always be the case for this script) and attach event listeners to the ‘Opened’ and ‘Closed’ fields so that their time picker would be set to midnignt.

‘Set Date Picker Time’ Client Script
Name: Set Date Picker Time
Table/Catalog Item/Variable Set: Wherever you need it!
Type: OnLoad
Script:

function onLoad() {
   //Set the date picker default time to '00' for 'Opened' and 'Closed' fields
   setDatePickerTime('opened_at');
   setDatePickerTime('closed_at');
}

function setDatePickerTime(field){
   //Attach an event listener to set default time value for date picker
   Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
      setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
   });
}
By | 2018-07-09T14:59:58-06:00 June 28th, 2011|Categories: Client scripts|Tags: , , |39 Comments

About the Author:

39 Comments

  1. Angelia Towler June 28, 2011 at 4:46 am - Reply

    This is perfect!!!

    Thanks

  2. Xavier Brumioul June 28, 2011 at 7:34 pm - Reply

    Great!

    this event.observe is really a wonderful thing!

    I will test you script right now.

    Thank you

  3. Xavier Brumioul June 28, 2011 at 7:52 pm - Reply

    it works great, but there is a small problem, if you have already a date time set, the time value is erased by 00:00:00.

    I’ll put a if g_form.getValue(‘opened_at’) == “”

    or somthing like that to avoid that.

    Thanks again for this great script

  4. Mahira January 19, 2012 at 12:06 am - Reply

    Hi Mark,
    Is there a way i can force the user to select the date only through the date picker and prevent manual entry?

    ~Mahira

    • Mark Stanger January 19, 2012 at 7:22 am - Reply

      You should be able to do this by using the following in a client script…

      g_form.getControl('start_date').readOnly='true';

      The only downsides to this is that there would be no way to clear the field once a date had been populated. Users would also be able to bypass this through a list edit so you’d need to lock down list edit permissions for the field using an ACL as well.

      • Trinu January 23, 2012 at 2:04 am - Reply

        Hi Mark,

        Even i have the similar problem.like not to allow the user to manually enter date-time.
        but when I tried using the script g_form.getControl(‘start_date’).disabled=’true’; to my surprise the data in date/time field is not being populating once i save it.

        • Mark Stanger January 23, 2012 at 6:50 am - Reply

          You’re right. You should use ‘readOnly’ in place of ‘disabled’ to avoid this issue. I’ve changed my comment from ‘disabled’ to ‘readOnly’ as well to avoid confusion.

  5. Ash February 3, 2012 at 8:22 am - Reply

    Hi Mark,
    Where should I get the all elements like GwtDateTimePicker_hh of calender?

    • Mark Stanger February 3, 2012 at 8:31 am - Reply

      There’s not a listing of all of the elements. You can use a dom inspector (like firebug) to get the element IDs though.

  6. Ash February 5, 2012 at 10:40 pm - Reply

    Thank you Mark,
    Hope ,this will help me to shade only freeze dates in Calender…

  7. Ash February 17, 2012 at 4:56 am - Reply

    Hi mark,
    I want to shade only the freeze dates in calender while picking dates for a task in a change.
    Can you tell me How to compare all the calender dates with freeze schedule dates…?

    • Mark Stanger February 17, 2012 at 5:44 am - Reply

      I’m not aware of a way to do that off-hand. You might try asking on the forums.

  8. Eric LeMonnier August 7, 2012 at 12:33 pm - Reply

    We have recently upgraded to the Berlin CA and we’ve been going through testing functionality. Have you noticed that the Berlin CA breaks the functionality of this script? Have you found a work-around? I’ll post more info as I diagnose it.

    Thanks

  9. Mark Stanger September 20, 2012 at 1:11 pm - Reply

    @Steve, I think it’s working correctly. Are you sure you’re using the correct field names? The script on demo11 doesn’t look like it’s using valid field names.

  10. Steve H September 20, 2012 at 2:01 pm - Reply

    Thanks Mark!!
    That was our issue as we are predominately an IE shop.
    It also appears that our sandbox instance must have an error as your fix did not work at all, but as a last resort, I went ahead and updated the script in our Dev instance and it works like a charm. Thanks for following up when you didn’t have to…

  11. Richard November 19, 2012 at 7:57 am - Reply

    Very nice for setting the hours, minutes and seconds. Any thoughts on similar setting the date – I’ve been asked to arrange, on the Change form, for the Planned End Date to default to the same date as Planned Start Date. Peering darkly into the client code, the issue seems to be that it creates a GwtDateTimePicker object, but tragically throws away the reference 🙁

    Any ideas, short of just copying Planned Start Date across to Planned End Date in an onChange client script, which is not terribly nice.

    • Mark Stanger November 24, 2012 at 6:25 am - Reply

      Nothing else comes to mind at the moment unfortunately. I don’t see any obvious hooks for doing that.

  12. deb April 11, 2013 at 5:56 pm - Reply

    Hi. I used this script for a number of date/time fields on our Change form, but I am experiencing a strange issue:

    I have an additional client script that is highlighting conditionally mandatory fields (ridiculous? yes – but necessary), and when I activated the script for the date/time picker, that script stopped working … for everyone except admins. I have absolutely zero idea why that would be, but when i turn off the date/time picker script, my field highlights work again.

    Any thoughts?

    script as written:
    function onLoad() {
    //Set the date picker default time to ’00’ for ‘Opened’ and ‘Closed’ fields
    setDatePickerTime(‘start_date’);
    setDatePickerTime(‘end_date’);
    setDatePickerTime(‘u_target_date’);
    }

    function setDatePickerTime(field){
    //Attach an event listener to set default time value for date picker
    Event.observe($(g_form.getControl(field).id).next(‘a’), ‘click’, function() {
    setTimeout(“$(‘GwtDateTimePicker_hh’).value = ’00’;$(‘GwtDateTimePicker_mm’).value = ’00’;$(‘GwtDateTimePicker_ss’).value = ’00’;”,0);
    });
    }

    • deb April 11, 2013 at 6:48 pm - Reply

      additional notes:

      we are at Berlin release – I’ve seen other reports of this not working on the SN forum, but it worked just fine when it was active – set zeros for HH MM and SS values.

      • Mark Stanger April 11, 2013 at 10:30 pm - Reply

        I don’t think it has anything to do with the Berlin release if it’s working fine in absence of the other script. My guess is that there’s some sort of timing or conflict issue between the two. You might try putting the code inside your ‘onLoad’ script inside of a try/catch block to see if that helps.

      • Richard Huss September 2, 2013 at 9:09 am - Reply

        This is months late, but I’ve just been debugging an issue of precisely this kind.

        The key difference between admin and non-admin users, in my case, was that the admin users had write access to the date fields and the non-admin ones didn’t. That meant the calendar picker icon and its surrounding link element, which normally appears immediately after the HTML input element, wasn’t there for the non-admins.

        This is correct behaviour, but the setDatePickerTime function was failing in this case (where the field was read-only and the link absent) as it just assumed that the next(a) call would return an element.

        My quick fix for the function just adds a check for the existence of the hyperlink:

        function setDatePickerTime(field){
        //Attach an event listener to set default time value for date picker
        var linkElement = $(g_form.getControl(field).id).next(‘a’);
        if (linkElement !== undefined) {
        Event.observe(linkElement, ‘click’, function() {
        setTimeout(“$(‘GwtDateTimePicker_hh’).value = ’00’;$(‘GwtDateTimePicker_mm’).value = ’00’;$(‘GwtDateTimePicker_ss’).value = ’00’;”,0);
        });
        }
        }

  13. David January 8, 2014 at 5:30 am - Reply

    We have a problem with the translation of the days in the datepicker. Any idea what the field names are for the one letter week day codes ?

    • Mark Stanger January 8, 2014 at 6:04 am - Reply

      As far as I know those aren’t translatable. You’ll probably need to contact ServiceNow support to request an enhancement.

  14. Anthony October 14, 2014 at 6:05 am - Reply

    Brilliant Mark!

  15. Troy April 3, 2015 at 7:23 am - Reply

    Hi Mark,

    That script works great! Thanks for posting that. I’m using a 12 hour format so I need to set the time to 3:00 pm. It’s setting to 3:00, but am. Is there a way to set it to pm? Thanks again for your help.

    • Mark Stanger April 3, 2015 at 7:52 am - Reply

      Sure. That’s just another element. You should be able to add this line to your script to set that.

      $(‘GwtDateTimePicker_ampm’).value = ‘PM’;

  16. Irene April 3, 2015 at 8:00 am - Reply

    I implemented this script last year in Calgary, and it has been working great. However, in Fuji it does not appear to work at all. Any suggestions?
    Thanks!

    • Mark Stanger April 3, 2015 at 9:11 am - Reply

      I’ve looked at this in Fuji and I’m not sure there’s a fix unfortunately. This script depends on being able to listen to the ‘click’ event on that icon. It attaches the listener correctly, but ServiceNow doesn’t seem to be triggering the ‘click’ event on those icons in the same way. You might just have to ask ServiceNow if they have another way to set the default picker time for a particular field.

      • Ahmed Hmeid July 23, 2015 at 6:12 am - Reply

        Had a look into this and looks like the UI renders fractionally slower in Fuji than in Eureka, so the timeout 0 was failing. Also, the DOM has changed so it could not find the element. So changed the setting function to try repeatedly until it finds the element, and also updated the DOM selector to find the element. Seems to do the trick:

        setDatePickerTime(‘dateField’);

        function setDatePickerTime(field){
        //Attach an event listener to set default time value for date picker
        Event.observe($(g_form.getControl(field).id).next().down(), ‘click’, function() {
        setTimeout(setDefaultTime,0);
        });
        }
        function setDefaultTime() {

        if (!$(‘GwtDateTimePicker_hh’)) {
        setTimeout(setDefaultTime,0);

        }
        else {
        $(‘GwtDateTimePicker_hh’).value = ’01’;
        $(‘GwtDateTimePicker_mm’).value = ’02’;
        $(‘GwtDateTimePicker_ss’).value = ’03’;
        }

        }
        }

  17. steve H July 9, 2015 at 2:39 pm - Reply

    Mark,
    Have you seen this post?
    Shannon seems to have found a workaround for Fuji.

    On checking the syntax, I get the “WARNING Implied eval is evil. Pass a function instead of a string.” error on the setTimeout line, but I also have that error on Eureka, so I am not sure it means much.

  18. Tina February 26, 2016 at 7:19 am - Reply

    I have tried multiple versions of this script with no success. Has anyone been able to get this script working in Fuji or have another alternative to defaulting the time of the dateTimePicker?

  19. Cynthia March 10, 2016 at 8:24 am - Reply

    We are skipping Fuji and going directly from Eureka to Geneva and just discovered it is not working there either. Anybody have any luck on an alternative yet?

    • Jacques P. April 15, 2016 at 7:53 am - Reply

      Hi Cynthia,

      We are on Geneva and I just tried the solution given by Ahmed Hmeid on 23-07-2015, 06:12 (3 posts above yours).

      It works perfectly!

Leave A Comment