Getting the "floor" of a timestamp and writing this to a tag

Suppose I have a script that, when triggered, writes system.date.now() to a memory tag. It always fires roughly around when a shift begins (this time/day varies constantly based on our production schedule). This memory tag's value can end up being any timestamp from (using first shift today as an example) 2024-02-14 7:00:00 AM up to 7:10:00 AM (or sometimes taking even longer). It will never fire early (e.g. system.date.now() in this context will never output 6:59:XX values or below).

I'm wondering if someone can help me modify the script such that the system.date.now() timestamp rounds down to the nearest hour before the tag write occurs, if that makes sense? I reviewed the system.date functions and can conceive of a couple ways to do this by converting from java, parsing a string, and so on, but anything I come up with gets convoluted pretty quickly. I'm basically in search of an equivalent floor() function but for timestamps. The transforms would specifically look like this:

now() [Input]            Output
 2024-02-14 7:07:39 AM    2024-02-14 7:00:00 AM
 2024-02-14 2:01:15 PM    2024-02-14 2:00:00 PM
 2024-02-15 1:00:45 AM    2024-02-15 1:00:00 AM
2024-02-15 12:30:02 AM   2024-02-15 12:00:00 AM

Any ideas?

Hmm. Maybe something like:

 def round_nearest_hour(timestamp):
    time = timestamp.getTime()
    time = time - (time % 3600)
    return java.util.Date(time)

(untested)

1 Like

I would probably just:

system.date.setTime(date, system.date.getHour24(date), 0, 0)

Which you could also write out as an expression, for performance.

2 Likes

system.date.setTime() is the magic function I needed! I missed this when looking through the docs. Works great now, thank you!!