user1005633
user1005633

Reputation: 755

How to convert String to date object[without time]

I have a string which contains a date in YYYYMMDD format (e.g. 20130614), i want to convert it to date and print it like: 'Day Month Day Year' (e.g Fri Jun 14 2013). I tried to do this with SimpleDateFormat but it returns date and time(i don't want time) (e.g. Fri Jun 14 00:00:00 EET 2013).

My code is:

String tmpValue = "20130614";
Date date = (Date) new SimpleDateFormat("yyyyMMdd").parse(tmpValue);

Also, i want after print to convert it back to String with YYYYMMDD format. Is it possible?

Upvotes: 1

Views: 1751

Answers (2)

Paulo H. Hartmann
Paulo H. Hartmann

Reputation: 173

try:

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");  
Date data = new Date(format.parse(tmpValue).getTime());  

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272337

The Date class represents a date and time (it's confusingly named) so you'll get a time component regardless. The standard recommendation for a useable and intuitive date/time API is to use Joda, which gives you these specific models.

To answer your second question, you can convert that back to a string using SimpleDateFormat again (check the doc). As before, I would recommend Joda here since the SimpleDateFormat class is (counter-intuitively) not thread-safe!

Upvotes: 5

Related Questions