Disclaimer

The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer, Avanade.

Search
Recomends...
  • Code Complete, Second Edition
    Code Complete, Second Edition
    by Steve McConnell
Login
« Using a Custom List to Store Configuration Data | Main | E-Mail Hosting »
Saturday
Sep292007

SharePoint 2007 Custom Date Time Field to default the time to the current time

The built in Date Time Column type for SharePoint 2007 lists has an interesting problem that I was surprised to find out about. When you create a new Date Time column, you are given the option to set the default value to Today's Date. This works fne if all you care about is the date, but if you want the time to default to the current time you are out of luck. Every time you create a new list item, the time for that column will always be defaulted to 12:00 AM.

Being the developer that I am, I looked for a solution but didn't find any point and click work arounds so I resorted to creating by own custom field type.

It looked straight forward enough, I only needed to write one class, Gac it and create one xml file and add it to

The Class:

    public class DefaultDateTimeFieldType : SPFieldDateTime
    {
        public DefaultDateTimeFieldType(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            this.Type = SPFieldType.DateTime;
        }

        public DefaultDateTimeFieldType(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
            this.Type = SPFieldType.DateTime;
        }


        public override string DefaultValue
        {
            get { return DateTime.Now.ToString("MM/dd/yyyy hh:mm tt"); }
            set {  }
        }

        public override object DefaultValueTyped
        {
            get { return DateTime.Now; }
        }
    }

You may notice that I am setting the Type property in each of the classes constructors to SPField.DateTime. It was an educated guess that had me add that line of code. Originally I didn't have it and the field worked fine until someone tried to edit a list item that contained the custom field type. You can create a new list item with no problem. You could view the values of existing items with no problems. But as soon as you tried to edit the list item, it threw an invalid cast exception.

I started looking through all the properties of the base type, and made a good guess, because as soon as I added that line of code it worked.

Anyway, besides gacing an assembly with that class, you also need to to add an xml file to the following directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\template\XML

The contents of the file are as follows:

<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
    <FieldType>
        <Field Name="TypeName">DefaultDateTime</Field>
        <Field Name="ParentType">DateTime</Field>
        <Field Name="TypeDisplayName">Default Date Time</Field>
        <Field Name="TypeShortDescription">Default Date Time</Field>
        <Field Name="UserCreatable">TRUE</Field>
        <Field Name="ShowInListCreate">TRUE</Field>
        <Field Name="ShowInSurveyCreate">TRUE</Field>
        <Field Name="ShowInDocumentLibrary">TRUE</Field>
        <Field Name="ShowInColumnTemplateCreate">TRUE</Field>
        <Field Name="SQLType">datetime</Field>
        <Field Name="FieldTypeClass">DefaultDateTimeFieldType, XXXASSEMBLYNAMEXXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXXPUBLICKEYXXX</Field>       
        <Field Name="Sortable">TRUE</Field>
        <Field Name="Filterable">TRUE</Field>
    </FieldType>
</FieldTypes>

In order to GAC you need to strong name your assembly. Update the xml file above to reflect the public key and assembly name you are using. Remember to reset IIS after putting your dll in the gac and adding this xml file.

One caveat to this approach is that the column will be uneditable in DataSheet mode. This is a problem with all custom field types.

Happy coding.

PrintView Printer Friendly Version

EmailEmail Article to Friend

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments (17)

hi david
thanks for your great post.
how to use this approach for internal DateTime type like this :
<FieldType>
<Field Name="TypeName">DateTime</Field>
<Field Name="InternalType">DateTime</Field>
<Field Name="TypeDisplayName">$Resources:core,fldtype_datetime;</Field>
<Field Name="SQLType">datetime</Field>
<Field Name="FieldTypeClass">DefaultDateTimeFieldType, XXXASSEMBLYNAMEXXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXXPUBLICKEYXXX</Field>
<Field Name="ParentType"></Field>
<Field Name="Sortable">TRUE</Field>
<Field Name="Filterable">TRUE</Field>
</FieldType>
June 23, 2008 | Unregistered Commenternader
I'm not sure what you are asking here?
June 25, 2008 | Registered CommenterDavid San Filippo
I found that in Sharepoint 2 the Date Time defaults to the nearest 5 minutes.
If you display both date/time as an option to enter, you see date widget with separate dropdowns for hour and minutes, the minutes being in increments of 5, Hence the problem trying to assign a correct time to an issue is not easily done.
June 26, 2008 | Unregistered CommenterW
hi,
sorry for my bad english!
i want to change FieldTypeClass for internal datetime FieldType and not add any custom FieldType
June 27, 2008 | Unregistered Commenternader
Hi i tried out your method for creating a custom date time field , but it did not work at all.
June 30, 2008 | Unregistered Commenterraman007
It definitely works, I suggest you check that the assembly info in the xml you added matches the assembly that you gacced on the servers that includes the SPFieldDateTime class. You may need to reset iis, though I am not sure.
June 30, 2008 | Registered CommenterDavid San Filippo
I was looking for something like this in order to get current date and time in a list, but when I use this example the date, time and minute controls are blank when creating a list item.
July 15, 2008 | Unregistered CommenterFreeman
Forgive my ignorance but i don't know where to drop your code to implement your solution. How would i go about using your solution?
August 14, 2008 | Unregistered Commenteraaron
Can times be put on to the nearest minute instead of 5 minute intervals?
September 4, 2008 | Unregistered CommenterBenli1979
If you look at the code in the class itself, you should be able to provide whatever default value you want by modifying the value returned in the GetDefaultValue Methods.
October 7, 2008 | Registered CommenterDavid San Filippo
In agreement with aaron's post on August 14th, 2008, where do we drop this code into? I am assuming Designer but wehre exactly?
December 15, 2008 | Unregistered CommenterMariner
If you set the Type -property in the constructor to SPFieldType.DateTime SharePoint thinks that the field is an ordinary DateTime field. For example in the list settings page the field type reads "Date and Time", rather than "Default Date Time".

Instead, you should override the GetFieldValue -method like this:

public override object GetFieldValue(string value)
{
return DateTime.Parse(value);
}

I figured this out after a half a day reflector session :-P Part of the field type handling is hardcoded in the SPListItem class, but only for the build in field types. That's why custom SPField -deriving classes must behave differently than the build in ones, which seems quite a messy design to me.
April 24, 2009 | Unregistered CommenterJukka
I want to display current date and time in one submit field which not edit by user. please help
May 21, 2009 | Unregistered CommenterAlpesh
Current Date and Time is already in the "Created" field
August 26, 2009 | Unregistered CommenterDraX3D
Hello...

I am using Room & equipment reservation template. To reserve a room i have start date and end date. what i need is...

Start date : Should be equals to or greater than today's date & time. system should not allow any reservation done less then today's date & time.

how can i do that.

any help will be highly appreciated.

Thank you
September 7, 2009 | Unregistered Commenterzain
hi,
if you don't mind. can you share the step by step instruction on how to achieve this. i've tried out your solution but it didnt work. i wonder if i've missed things. since i'm very new with sharepoint and i need to create custom default value for my custom list fields. thanks
November 1, 2009 | Unregistered Commentermala
isnt share point an alpha product with nonsense like this? do the sharepoint developers have brains?
August 3, 2010 | Unregistered CommenterJelle

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.