[NTLUG:Discuss] verify that a text string is a valid date.

Chris Cox cjcox at acm.org
Thu Feb 2 10:47:04 CST 2006


Richard Geoffrion wrote:
> I'm trying to do something but I don't know what it is called.
> 
> I want to check to see if the first 10 characters of a file is a vaild 
> date...eg  2006-02-01  and if it IS..then I want to continue the process.
> 
> What am I trying to do in bash(or other utility terms)?  I don't know
> the name of what I'm trying to do so I'm finding it difficult to search.
> 

$ mydate="2006-02-01"
$ date -d "$mydate"
Feb 28 00:00:00 CST 2006
$ echo $?
0
$ mybaddate="2006-02-29"
$ date -d "$mybaddate"
date: invalid date `2006-02-29'
$ echo $?
1

Is that enough to go on?  I can show a more
programmatic example... sound like you know shell though.

In true bourne shell fashion, I can pick off the
first 10 characters of name like so (this would
work with GNU date using Solaris's bourne shell):

mydate=`expr "$name" : '\(..........\).*'`

or with ksh... could use:

mydate=${name%??????????}

or with bash:

mydate=${name:0:10}

(there are many ways to do this obviously)











More information about the Discuss mailing list