setSeconds odd behavior

I found an odd behavior when using setSeconds.

to explain better, I create a new window:
drop two components:

  • popup calendar
  • button

In the button, I added the following script

sDateTime = event.source.parent.getComponent('Popup Calendar').date
tDateTime = event.source.parent.getComponent('Popup Calendar').date

print sDateTime, type(sDateTime), sDateTime.getTime()
print tDateTime, type(tDateTime), tDateTime.getTime()

tDateTime.setSeconds(tDateTime.getSeconds()+1)
print "tDateTime:", tDateTime

Basic I assign the [Popup Calendar] date to two variables [sDateTime and tDateTime]

I added 1 second to the variable [tDateTime], but when I do that it also add 1 second to the Popup Calendar date.

So I am trying to understand this behavior, since this works fine in the script console, but when I use in the button, it keep changing the popup calendar value, which doesn;t make any sense since I am assigning the popup calendar value to a variable, and I am changing the variables.

if anyone has any inside or ideas on this please let me know.

thanks,

This is expected behavior.
The JVM (and thus, both Java and Jython) pass non-primitive values by reference.
So tDateTime is defined as ‘the date object attached to the popup calendar’. When you mutate that date instance, you’re manipulating the single object in memory that’s shared between your executing script and the popup calendar component.

If you want a unique instance, you need to create your own Date object. The easiest way to do this would be to convert the original object into its milliseconds-from-epoch representation, then create a new object from that:

tDateTime = system.date.fromMillis(system.date.toMillis(event.source.parent.getComponent('Popup Calendar').date))
2 Likes

I guess I lied a bit - the easiest way would probably be to call clone() on the instance, which returns a new object:

now = system.date.now()
print now, id(now)
now2 = now.clone()
print now2, id(now2)

now.setSeconds(1)
print now, id(now)
print now2, id(now2)
>>> 
Tue Sep 13 09:52:16 PDT 2022 4
Tue Sep 13 09:52:16 PDT 2022 5
Tue Sep 13 09:52:01 PDT 2022 4
Tue Sep 13 09:52:16 PDT 2022 5

However, clone is a bit weird and won’t work on most object types, so I’d probably still just pass to/from milliseconds in this case.

1 Like