Anders
Anders

Reputation: 878

Simple java date conversion

Having some troubles and can't find a quick answer..

Im trying to store a date within a string, and later fetch it to convert it back to a date.

However when storing the date using:

string tmp = new Date().toString();

And then trying to convert it back using

Date date = new Date(tmp);

I get the Exception type

 java.lang.IllegalArgumentException

with my Android 2.2 device. Does work with 2.2 & 2.3 emus tho.

Any tips on what other way i can store and convert back?

Upvotes: 0

Views: 623

Answers (4)

Dharmendra Barad
Dharmendra Barad

Reputation: 949

use SimpleDateFormat as shown below.

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");

//this will convert date into string.
String temp = formatter.format(currentDate.getTime());

//this will convert string into date format.    
Date date=(Date)formatter.parse(temp);

Upvotes: 0

dten
dten

Reputation: 2374

Do you need it to be a string? long is easier :)

do

long time = new Date().getTime();

Date date = new Date(time);

then you dont' have to parse

Upvotes: 2

evilone
evilone

Reputation: 22740

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

// to string
String dateStr = formatter.format(new Date());

// to date 
Date date = formatter.parse(dateStr);

Upvotes: 1

Xavi López
Xavi López

Reputation: 27880

You could use SimpleDateFormat with its methods parse() and format().

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS");
String tmp = sdf.format(new Date());
Date date = sdf.parse(tmp);

Upvotes: 3

Related Questions