Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting date

Status
Not open for further replies.

peritas

Technical User
Sep 2, 2002
1
DE
I have the following field in a script which is pulling the DATE out of a table in the RTD. It pulls the date out as "20020902" but I need it in the format "2 Sep 2002"

set date [$prcSnapRecord get DATE]

Thanks


 
Well, after looking at the wiki (I didn't see anything immediately on subject so...

If you know that the date string format is yr/mo/day,
that the year is four digits, that the month will be
two chars and that the day needs a leading
zero removed if one exists an answer is to
code a couple of functions todo the translation.

proc num_to_month {dstr} {
array set months {
jan 01
feb 02
mar 03
apr 04
may 05
jun 06
jul 07
aug 08
sep 09
oct 10
nov 11
dec 12
}
set ind [string range $dstr 4 5]

foreach i [array name months] {
if {"$months($i)" == $ind} {
return $i
}
}
}

proc rlz {dstr} {
if {[string index $dstr 6] == 0} {
return [string index $dstr 7]
}
return [string range $dstr 6 7]
}

then:
set final [format "%s %s %s" [rlz $dstr] [num_to_month $dstr] [string range $dstr 0 3]]
 
Try:

set date 20020902
puts [clock format [clock scan $date] -format {%d %b %Y}]

Magic!

ulis
 
Still got the leading zero on the day ulis ;)
Nice solution btw.
 
To take care of the possible leading "0" from ulis's solution, there are a couple of possiblities.

One is to use the "%e" descriptor instead of "%d".

Code:
set date 20020902
puts [clock format [clock scan $date]   -format {%e %b %Y}]

which gives us:

Code:
  2 Sep 2002

But note the leading " ". Also note that the clock reference page says that the "%e" descriptor "may be supported on some systems" (emphasis added). I'm not sure what systems wouldn't support it, though. It worked fine in Tcl 8.3.2 on Windows 2000 and Mandrake Linux 8.1 running Tcl 8.3.4.

The other way to handle the potential leading "0" from ulis solution would be to pass the result to string trimleft, to chop off any leading "0"s:

Code:
set date 20020902
puts [string trimleft [clock format   [clock scan $date] -format {%d %b %Y}] 0]

Which gives us:

Code:
2 Sep 2002
- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top