Example

Time and Date Stamps

Author: Carl Sassenrath
Return to REBOL Cookbook

This example shows some simple ways to create and save timestamps. This is useful if you need to keep track when an event occurred, such as the last time you downloaded a file from a server, or the last time you checked a website, etc. I also show how to create coded timestamps, such as those used for filenames.

Here is how to get the current date and time (with timezone) and save it to a file:


    when: now
    save %timestamp when

To load the timestamp back later:


    prior: load %timestamp

Here's a complete program that keeps a datestamp each time you run it:


    when: now
    if exists? %timestamp [
        prior: load %timestamp
        print ["It's been" when - prior "days"]
    ]
    save %timestamp when

You can create coded timestamps such as those used for creating unique filenames based on time. For example, sometimes you need to create filenames that have the form:


    YYYYMMDDHHMMSS

Where YYYY is year , MM is month, DD is day, etc. (It is done in this order so files names appear in chronological order in directories.)

Here's a function that will return a date and time coded string:


    to-timestamp: func [when /local stamp add2] [
        add2: func [num] [ ; always create 2 digit number
            num: form num
            if tail? next num [insert num "0"]
            append stamp num
        ]
        stamp: form when/year
        add2 when/month
        add2 when/day
        add2 when/time/hour
        add2 when/time/minute
        add2 when/time/second
        stamp
    ]

Here's what the result will look like:


    print to-timestamp now
    20030829104905

Now you can create a filename based on a date and time:


    file: to-file to-timestamp now
    save file the-data

I often use a variation on this function that will create a smaller filename by using letters as well as numbers (think of it as base-36 encoding, 10 numbers and 26 letters).


    to-timestamp: func [when /local stamp base add2] [
        base: "0123456789abcdefghijklmnopqrstuvwxyz"
        stamp: copy ""
        add2: func [num] [
            append stamp pick base num + 1
        ]
        add2 when/year - 2000
        add2 when/month
        add2 when/day
        add2 when/time/hour
        add2 when/time/minute / 2
        stamp
    ]

Note: this timestamp is only accurate to within two minutes. If you need greater accuracy, you will need to make minutes and seconds two digits (as in prior example). Do not try to extend the base string to 60 by adding uppercase characters, because not all operating systems distinguish upper and lower case in filenames.

The resulting string is now only five letters long:


    print to-timestamp now
    38tao

You can use the new function as you did before:


    save to-file to-timestamp now the-data

2006 REBOL Technologies REBOL.com REBOL.net