Hi all,

I would like to create a date object and specify a value. I am facing some defficulties.

Here's what I tried:

String dateString = "2005-04-29 00:00:00.0";
Date asOfDate = new Date(dateString);   // this gives Illegal argument exception.

I know that Date constructor with String as argument -- as I am using above -- is deprecated. Can someone tell me how I can achieve the same requirement without using the deprecated method, as above?

Please advise...

Thanks.

Recommended Answers

All 5 Replies

You can either use a Calendar and set the day, month, year, time values individually or if you have an existing string date that you need to parse you can create a SimpleDateFormat and use the parse(String) method to convert it to a Date object.

Thanks for quick revert.

I will try with SimpleDateFormat, I will update this thread accordingly.

Hi,

I have tried with SimpleDateFormat as follow:

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-mm-dd hh:mm:ss" );
Date date = sdf.parse("2005-05-29 00:00:00.0");
System.out.println("Date: " + date.toString());

But the output is not the way I want it, the out is like this:

Date: Sun May 29 00:00:00 EDT 2005

I want the out put to be the same as I specify in my SimpleDateFormat.e.g. (2005-05-29 00:00:00.0)

Can you comment on this, please.

Thanks.

Then use:
sdf.format(date);

The SimpleDateFormat.format(Date) will take any Date object, no matter how it was created and retutn a String based on the pattern you have set at the SimpleDateFormat object.
Meaning that this:

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-mm-dd hh:mm:ss" );
Date date = new Date();
System.out.println("Date: " + sdf.format(date) );

will return:
2008-03-14 15:53:45

Thanks man, it worked! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.