BitterCoder's Wiki

By default DateTime fields have a value of "12 AM" - if your want to change this, about the only method available to you is using javascript... here's some tips on how to get that working.

Edit

Calculate what the DefaultTime should be

I'm rendering the edit forms from a custom web part in this example, note the way we format the hour so that it will work for different regional settings ... you can skip this and hard-code it in the javascript if that's easier.

public int DefaultHour
{
    get
    {
        if ((_defaultHour < 0) || (_defaultHour > 23))
        {
            _defaultHour = 23;
        }
        return _defaultHour;
    }
    set
    {
        _defaultHour = value;
    }
}

public string DefaultTime { get { DateTime dt = new DateTime(2000, 1, 1, DefaultHour, 0, 0); return dt.ToString("h tt"); } }


Edit

The JavaScript

Here's the script (we call this from inside a web part, to register it) - alternatively you could stick it in-line within the page somewhere...

private void RegisterAlterDefaultTimeScript()
{               
            string script =
    @"<_script type=""text/javascript"">
function setSelectedOption(select, value) 
{
  var opts = select.options;
  var l = opts.length;
  if (select == null) return;
  for (var i=0; i < l; i++) {
    if (optsi.value == value) {
      select.selectedIndex = i;
      return true;
    }
  }
  return false;
}

function setDefaultTime() { var tags = document.getElementsByTagName(""select""); for (var i=0; i < tags.length; i++) { element = tagsi; if (element.id.indexOf(""_DateTimeField_DateTimeFieldDateHours"") > 0) { setSelectedOption(element, """ + DefaultTime + @"""); } } }

setDefaultTime();

</_script>";

if (!Page.ClientScript.IsStartupScriptRegistered("alterDefaultTime")) Page.ClientScript.RegisterStartupScript(typeof(FilteredListFormWebPart), "alterDefaultTime", script); }

ScrewTurn Wiki version 2.0.2. Some of the icons created by FamFamFam.