Search code examples
rebolred

How to get a formatted date and time string from `now`?


I'm using "Red Programming Language" version "0.6.4" on Windows and making a command line application.

I don't know much Red language and I don't understand many things. I did go over "work in progress" docs at (https://doc.red-lang.org/en/) before asking here.

I need to get a date and time string formatted as yyyymmdd_hhmm.

I've started with code like this:

Red []
dt: to string! now/year
print dt

which gives me 2019 but I need the other things month, day and time to obtain something like 20190608_2146

I tried also:

Red []
dt: to string! now/precise
print dt

which gives me 8-Jun-2019/21:47:51.299-07:00 but again what I needed was 20190608_2147

Question:
How to modify the code above to obtain something like 20190608_2147 from now?

Thank you.


Solution

  • I have written a script for Rebol and Red called 'Form Date' that will format dates/times in a similar fashion to STRFTIME. The Red version is here.

    do %form-date.red
    probe form-date now "%Y%m%d_%H%M"
    
    print first spec-of :form-date
    

    Within the script are individual snippets of code used for formatting the various components of a date! value.

    You don't need the script for your specific example though, you can extract and join the various components thus:

    date: now
    rejoin [ ; reduce-join
        form date/year
        pad/left/with date/month 2 #"0"
        pad/left/with date/day 2 #"0"
        "_"
        pad/left/with date/hour 2 #"0"
        pad/left/with date/minute 2 #"0"
    ]