Home > Archive > AWK > June 2007 > Date check
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Prateek 2007-05-18, 6:57 pm |
| Hi,
I have a requirement concerning date type. The date is required to be
stored in MMDDYYYY format. I need to see if the value entered for
MMDDYYYY is a valid date as sometimes people confuse it with DDMMYYYY
or they might enter an alphanumeric value. So assuming the date is
stored into a variable, can you please recommend how do i go ahead
from here.
My attempts until now:
I have used substr() function to retrieve the day, month and year from
the MMDDYYYY format variable. Can I use any timestamp based functions
which would solve this for me instead of me manually checking if day
is less 31, month < 12 and so on. There could be a better approach
than my attempted code solution and if so, please feel free to let me
know.
Thanks,
Prat
| |
| Ed Morton 2007-05-18, 6:57 pm |
| Prat wrote:
> Hi,
> I have a requirement concerning date type. The date is required to be
> stored in MMDDYYYY format. I need to see if the value entered for
> MMDDYYYY is a valid date as sometimes people confuse it with DDMMYYYY
> or they might enter an alphanumeric value. So assuming the date is
> stored into a variable, can you please recommend how do i go ahead
> from here.
>
> My attempts until now:
> I have used substr() function to retrieve the day, month and year from
> the MMDDYYYY format variable. Can I use any timestamp based functions
> which would solve this for me instead of me manually checking if day
> is less 31, month < 12 and so on. There could be a better approach
> than my attempted code solution and if so, please feel free to let me
> know.
>
> Thanks,
> Prat
>
"A valid date" is very different from "A valid date format" and, given
someone enters "02032007" how would you prove that they meant Feb 3rd vs
March 2nd?
Assuming you're happy with just checking "A valid date format" there's
no builtin way to do it in awk. Even in GNU awk, mktime() doesn't check
that you pass it a valid time, but what you can do is use mktime() to
convert the given date to a seconds from the epoch, then use strftime()
to convert it back and then see if it's the same value it started with,
e.g.:
awk 'BEGIN{date="02032007"; print date " is " (date ==
strftime("%m%d%Y",mktime(substr(date,5,4)" "substr(date,1,2)"
"substr(date,3,2)" 0 0 0")) ? "good" : "bad") }'
If you don't have GNU awk and don't care about how many days can be in a
specific month but just that it's always between 1 and 31, this might be
a good enough check:
awk 'BEGIN{date="02032007"; print date " is "
date~/^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])([0-9][0-9][0-9][0-9])/ ?
"good" : "bad" }'
Regards,
Ed.
| |
|
|
|
|
|
|
|
|
|