• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

parsing a date from command line

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's my problem: the user enter's a date in the command line. I want to take that date, in whatever date format it happens to be in, and reformat it into a standard date format of: "dd-MMM-yy". Because the possibilities are endless as to what the user might enter, how do i account for so many variations? Many possible dates IN --> one OUTcome.
 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have to have some guidelines as to the formatting. For example - you cannot allow the user to enter dates as
dd/mm/yy
mm/dd/yy
yy/mm/dd - all at the same time. No compiler can then possibly say what 01/02/03 means.
Once you decide what are the allowable formats e.g
dd/mm/yy
dd/mm/yyyy
dd/mon/yyyy
dd/month/yyyy
All the above with - & . seperator etc. etc.
Then you have to write a method that parses for all these cases. For example you have to check the seperator chars and tokenize the string into 3 fragments. Then check value of first fragment. If it is digit and within 31(max possible value of dd) etc.
Let us know how it goes.
 
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The DateFormat class has a method to parse a date string into a Date. There is no need to tokenize the string and parse it yourself, as Sunetra described.
There are 4 instances of this class that you can use: SHORT, MEDIUM, LONG, and FULL. Each instance parses several different input formats. See the API docs for more information on these formats.
I can't guarantee that there is a way to accept ALL possible inputs, but this should come pretty close:

The try/catch code is a little messy, but it shows the general idea.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic