Forum OpenACS Q&A: Date Math: How to...

Posted by Bob OConnor on

How do I do date math in tcl and pg? Ok perhaps it's documented somewhere...pointers also appreciated.

  • Take Start_date and add 7 days to it.
  • Take Start_date and change the time to Midnight of the next day.
  • Take today and subtract Start_date to give number of days with one decimal Example: 4.8 days
  • Same as above but rounded down to 4 days. It doesn't become 5 days until 5 days have elapsed.

Thank you. -Bob

Posted by Don Baccus on
You could probably do much worse than to begin by reading the Postgres  documentation section on date types and operators.
Posted by Michael A. Cleverly on
If you want to do date math in Postgres you should do as Don suggests and take a look at the Postgres docs. You can do some date arithmetic in Tcl -- anything contemporary: 1970 to 2038. Beyond that you'd have to start jumping through hoops to fudge things.

If you want to do date math in Tcl then you need to read up on the clock scan command. If you have tclsh installed locally, drop to a shell and run the command "man n clock". Given a date/time clock scan will return the number of seconds since the beginning of the epoch. You can then use regular arithmetic (i.e. expr) to add days. (There are 86,400 seconds in a day.) Then use clock format or ns_fmttime to convert back to a date (formatted as you'd like).

Be aware that the clock scan command in Tcl 8.x can parse a wider range of date formats than the Tcl 7.6 version can, so depending on how you write your code it may not work under both nsd76 and nsd8x. If you are still using AOLserver 2.3 (Tcl 7.4) there is no clock scan command. You could use ns_parsehttptime (if you can get your initial date into HTTP time format to begin with).