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

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer Service forum

Set arbitrary date from string with custom pattern in C# plugin

(0) ShareShare
ReportReport
Posted on by 131

I'm trying to set a date field from a C# plugin. I have a string, and a custom date pattern. The date is always showing up in UTC time instead of EST.

I've tried using EST in my dateString and format. I've tried converting to UTC using DateTimeStyles.AdjustToUniversal and ToUniversalTime().  I've tried using DateTimeOffset instead of DateTime. 

I know that I need to adjust my dateString before I set the field but not sure how. 

The following code results in a time of 12:20 PM.  Which makes sense because the current offset for UTC is -4

string dateString = "2019-12-30 4:20 PM";
string format = "yyyy-MM-dd h:mm tt";
try
{
DateTime myDate = DateTime.ParseExact(dateString, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None);
entity["field"] = myDate;
}
catch
{
throw new InvalidPluginExecutionException(dateString + " is an invalid date format");
}

Categories:
I have the same question (0)
  • Iron Arm Profile Picture
    131 on at

    I think I know what's going on.  That code is setting the time in UTC, and when page renders in CRM it converts it to my timezone (EST).  So I need to convert to local time before setting it.

  • Iron Arm Profile Picture
    131 on at

    Got it working

    DateTime myDate = Convert.ToDateTime(dateString).ToLocalTime().ToUniversalTime();

  • Iron Arm Profile Picture
    131 on at

    I lied.  Doesn't work.  My plugin fires post operation on email create.  Funny, I made the plugin fire on the "assign" event for troubleshooting and it works.  It also works if I set the time to local time in the plugin, but that's not best practice since everything is stored in UTC

  • Suggested answer
    Iron Arm Profile Picture
    131 on at

    Got it working.  You have to convert from the time zone to UTC

    TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

    DateTime newTime = TimeZoneInfo.ConvertTimeToUtc(myDate, est);

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

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Customer Service

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans