Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 31, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Parsing a string into a date

I'm writing a class that reads a log file containing timestamps. My StringTokenizer returns the timestamp as a String and I then have to store it in a date container. Should I use Date or GregorianCalendar? Also, how do I use DateFormat to parse the timestamp?

The first question is difficult to answer. Normally I would say use GregorianCalendar because so much of the Date class is deprecated. However, when you parse the timestamp string using DateFormat, you'll end up with a Date object. The basic rule is that if you need to modify, add and substract your times, you should use a Calendar instance. If you need a read only date representation that can be compared to other dates, then the Date class is usually sufficient, but you probably should still stick to a Calendar instance.

To parse the timestamp, use the parse() method in DateFormat. First create a DateFormat that uses the default locale and style. You can do this by calling the getDateInstance() static method in DateFormat. Now simply invoke the parse() method in the resulting DateFormat instance. parse() will understand most common date representation formats, but if your log timestamps are in a format it doesn't understand, you might have to write your own parser. The parse() method returns a Date instance. You can convert a Date to a Calendar with the Calendar setTime() method.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date