Extend/Assign DateTime

I have a pair of setter/getter methods I wrote for Date to extend it to deal with ISO8601 times in strings. The setter extends Date and assigns the value of the passed ISO8601 string to the passed-in date object, which worked fine when it was possible to set the fields… I’ve rewritten it for DateTime, but how do I effect the “assigns” part? Assigning a new DateTime constructed from the extracted date/time elements to the passed-in “extends” variable doesn’t work. I guess I could construct a new DateTime object with the value I want, .ToString it, and then .FromString it back to the original assigns variable, but that seems somewhat roundabout. Is there a right way to do this?

Could you post some code showing what you’d like to be able to do?

I’d like to extend DateTime with a computed .ISO8601 property implemented with a getter/setter pair. The getter returns the DateTime’s value in ISO8601 format (optionally takes a format spec), while the setter sets the DateTime’s value from an ISO8601 date string.

The method definitions look like:
ISO8601(extends d as datetime, optional fmt as string = "YMDhmsZ-")
ISO8601(extends d as datetime, assigns dateval as string)

You’d use them like this:

var d as DateTime
...
someISO8601String as string = d.ISO8601   'get the DateTime value as an ISO8601
...
d.ISO8601 = someISO8601String    'set the DateTime from an ISO8601

The setter implementation parses the 8601 string, getting all of the elements of a DateTime and then needs to end by assigning them to the DateTime. I’ve tried

d = new DateTime(...)

and

ddd = new datetime(yy,mm,dd,floor(hh),floor(mi),floor(ss),ns,tz)

d = datetime.FromString(ddd.SQLDateTime,nil,tz)

Neither seems to “stick” on the return (I assume because we’re really making a reference to a new DateTime so “assigning” it to the reference in the calling context doesn’t actually happen).

Can work around by just making a regular method to create a DateTime from a string.

Should add this is an API2 conversion from the same methods implemented for Date, which allowed you to assign the individual properties of the date.

Right. So DateTime (unlike Date) really is immutable. That means that you can’t change them in place.

That said, you could create your own wrapper for DateTime which stores a DateTime under the hood, returns the DateTime with Operator_Convert and then add your methods to that class. It’d be a bit of work to add all of the methods, but it could be generic enough to share among projects.

Greg, thanks for confirming and offering an option for a solution, which I’ll mark here for others to find. In my case, I converted it to a standalone function that returns a new DateTime from an ISO8601 string.

1 Like