Is there anyway to convert say Dec 12 08:26:03 EST 2023 to the current Date with the old time (Dec 18 08:26:03 EST 2023)??
Yes there is.
Where are you trying to do this? In an expression or in a script?
A script
Something like this should work:
daysDiff = system.date.daysBetween(date1, date2)
newDate = system.date.addDays(date1, daysDiff)
What if I do not know that date2, for example if I have date1 = DEC 12 8:26:03 - I want to dynamically turn that into DEC 18 8:26:03 - I do not have DEC 18 8:26:03
inBetween = system.date.minutesBetween(last_sample_time, system.date.now())
next_sample_time = system.date.addMinutes(last_sample_time, inBetween)
this would end up comparing to the current date and give me a result that is not accurate
Why are you calculating in minutes? Calculate in days.
You can use the system.date.midnight()
function if you want to bring both dates to midnight before calculating daysBetween
.
system.date.setTime(
system.date.now(),
system.date.getHour24(last_sample_time),
system.date.getMinute(last_sample_time),
system.date.getSecond(last_sample_time)
)
https://docs.inductiveautomation.com/display/DOC81/system.date.setTime
https://docs.inductiveautomation.com/pages/viewpage.action?pageId=58603995
Ah!
inBetween = system.date.daysBetween(system.date.midnight(last_sample_time), system.date.midnight(system.date.now()))
next_sample_time = system.date.addDays(last_sample_time, inBetween)
This should achieve what I want. Does this work for the edge case of it being AM or PM ?
Would this be a better solution for the edge cases of daylight savings, different month lengths, time zone changes ???
I would expect there to be less "surprises" with the setTime
approach - it's going to give you the time you "expect" with the given algorithm. Subtracting days may have DST/timezone complications. In general, though, date math is complicated, and there is no single perfect solution. You're always leaving something off the table.
Thanks! @PGriffith and @Transistor