Compare Date & Time in C#

ATTENTION: This forum is no longer active. Please navigate to our new support site at https://support.starfishetl.com/
Viewing 4 posts (of 4 total)
srijanapokharel
User - Author
Post count: 27
#1

Hi,
How would I write a C# code to compare 2 datetime columns? Both the fields could be empty. I am using DateTime.Compare method.

object ScriptedField()
{
DateTime dt1=new DateTime(Convert.ToDateTime(Starfish.OriginData[DATECREATED]));
DateTime dt2=new DateTime(Convert.ToDateTime(Starfish.OriginData[DATECOMPLETED]));
int result = DateTime.Compare(dt1, dt2);

if(result>0)
{
//return DateCompleted
}

else
{
//return DateCreated
}

}

Thanks for your help!

Comments (4)

srijanapokharel's picture srijanapokharel
User - Author
Post count: 27
#2

object ScriptedField()
{
string DateCompleted = Convert.ToString(Starfish.OriginData[DATECREATED]);
DateTime datecre = DateTime.Parse(Starfish.OriginData[DATECREATED].ToString());
DateTime datecomp = DateTime.Parse(Starfish.OriginData[DATECOMPLETED].ToString());

if (datecre < datecomp)
{
if (!String.IsNullOrEmpty(DateCompleted))
{
DateTime timeUtc = DateTime.Parse(Starfish.OriginData[DATECREATED].ToString());
TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime pstTime = TimeZoneInfo.ConvertTime(timeUtc, pstZone,TimeZoneInfo.Local); //Converts the time from mentioned time zone to local time zone

return pstTime;
}
else
{
return "";
}
}
}

I get the System.NullReferenceException: Object reference not set to an instance of an object error. Will you please help me figure this out. Thanks!!

Log in to post comments
Aron Hoekstra's picture Aron Hoekstra
Administrator
Post count: 2
#3

I could take a look - could you supply some sample values that you're using?

Log in to post comments
Aron Hoekstra's picture Aron Hoekstra
Administrator
Post count: 2
#4

I just tested your code with some made up date values and it appears to be functioning correctly. Are you sure there weren't any null's in the origin data? Also, in Admin, Starfish may not resolve those variables to anything useful in the check function.. Please try actually running it (even just in preview) to see if the error goes away. The NullReference could be related to the Starfish.OriginData[] object because its in the Admin.

Log in to post comments
srijanapokharel's picture srijanapokharel
User - Author
Post count: 27
#5

Thanks much for your response. Apparently the code seems to be working when you run the job. It was just erroring out when I do "Check" on the function field.

Log in to post comments
Viewing 4 posts (of 4 total)

Forum Login

Login or sign up for our forums to connect to the user community.

Reply

You must log in to post.

Not a Member? Register.