web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Service | Customer Service, Contact Center, Fie...
Suggested Answer

Convert date/time field to date only

(0) ShareShare
ReportReport
Posted on by 160

Hi.

I have a field was in date/time format. i change it to date only format and set to date only for field behavior also. Now, i want to how can i change the old records that are saved in date/time in database to "date only" by C# code.

kind regards,

I have the same question (0)
  • Suggested answer
    Community Member Profile Picture
    on at

    Hi,

    You can use CrmServiceClient to get and update records in CRM. Here are some code samples:

    using(var svc = new CrmServiceClient(connectionstring))
       {
                CreateRequiredRecords();
    
         // Instantiate an account object.
         // See the Entity Metadata topic in the SDK documentation to determine
         // which attributes must be set for each entity.
    
               var account = new Account { Name = "Fourth Coffee" };
    
         // Create an account record named Fourth Coffee.
               _accountId = svc.Create(account);
               Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
    
         // Retrieve the account containing several of its attributes.
               var cols = new ColumnSet(
               new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });
               Account retrievedAccount = (Account)svc.Retrieve("account", _accountId, cols);
               Console.Write("retrieved ");
    
         // Retrieve version number of the account. Shows BigInt attribute usage.
               long? versionNumber = retrievedAccount.VersionNumber;
               if (versionNumber != null)
               Console.WriteLine("version # {0}, ", versionNumber);
    
         // Update the postal code attribute.
               retrievedAccount.Address1_PostalCode = "98052";
    
         // The address 2 postal code was set accidentally, so set it to null.
               retrievedAccount.Address2_PostalCode = null;
    
          // Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
               retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
               retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
               retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);
    
          // Shows use of a Money value.
               retrievedAccount.Revenue = new Money(5000000);
    
          // Shows use of a Boolean value.
               retrievedAccount.CreditOnHold = false;
    
          // Shows use of EntityReference.
               retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);
    
               // Shows use of Memo attribute.
               retrievedAccount.Description = "Account for Fourth Coffee.";
    
               // Update the account record.
               svc.Update(retrievedAccount);
               Console.WriteLine("and updated.");
               DeleteRequiredRecords(promptforDelete);
               }

    Then you can use DateTime.ParseExact to convert the obtained date into a date-only format, and then update the field:

    public static DateTime ParseExact (string s, string format, IFormatProvider? provider);

    This is the code sample:

    using System;
    					
    public class Program
    {
    	public static void Main()
    	{
    		DateTime date = DateTime.ParseExact("9/1/2009", "M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);
    		Console.WriteLine(date.ToString("yyyyMMdd"));
    	}
    }

    If this helped you, I'd appreciate it if you'd mark this as a Verified Answer, which may in turn help others as well.

    Best Regards,

    Frank Gong

  • Nafas Profile Picture
    160 on at

    Hi. I write this code but when it runs successfully, the data does not change anymore.

    var request = new ConvertDateAndTimeBehaviorRequest()
    {
    Attributes = new EntityAttributeCollection() { new KeyValuePair<string, StringCollection>("pcm_contract", new StringCollection() {"pcm_startdate"}) },
    ConversionRule = DateTimeBehaviorConversionRule.SpecificTimeZone.Value,
    TimeZoneCode = 110,
    AutoConvert = false // Conversion must be done using ConversionRule
    };

    // Execute the request
    var response = (ConvertDateAndTimeBehaviorResponse)service.Execute(request);

    }

  • Suggested answer
    CRMJetty Profile Picture
    3,512 on at

    Hello,

    Try this one,

    https://www.inogic.com/blog/2015/07/updating-date-values-of-existing-records-after-modifying-the-datetime-behaviour-in-dynamics-crm-online-update-1/

    https://forums.asp.net/t/2003945.aspx?Convert+DateTime+in+C+into+Date+in+SQL

    I hope it helps,

    Thanks.

    Please mark as verified if the answer is helpful. Welcome to join hot discussions in Dynamics 365

  • Community Member Profile Picture
    on at

    Hi,

    Do you change the DateTime attribute’s Behaviour from User Local to TimezoneIndependent ? If you do, the datetime property value will not be converted if you execute the ConvertDateAndTimeBehavior request.

    If this helped you, I'd appreciate it if you'd mark this as a Verified Answer, which may in turn help others as well.

    Best Regards,

    Frank Gong

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Service | Customer Service, Contact Center, Field Service, Guides

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 45 Super User 2025 Season 2

#2
Daniyal Khaleel Profile Picture

Daniyal Khaleel 27 Most Valuable Professional

#3
Soundari Profile Picture

Soundari 15

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans