user663724
user663724

Reputation:

Help Needed with Date Format in java

I have My Database data in this format

18-NOV-10

I have to pass the same format into java.util.Date like this

Date date = new java.util.Date(dateformater);

so that the result of java.util.Date is like this 18-NOV-10

Is this possible ??

I tried this way

String strDate = "12-NOV-07";

    SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MMM-yy");

    Date date = sdfSource.parse(strDate);

    System.out.println(date);

But i am getting the result as "Mon Nov 12 00:00:00 IST 2007 " which i want it only 12-NOV-07"

Upvotes: 0

Views: 275

Answers (4)

Binil Thomas
Binil Thomas

Reputation: 13779

Try System.out.println(sdfSource.format(date).toUpperCase()); instead. The Date object will always have a time component to it; there is no way to "disable" that feature. What you can do instead is to ignore it in your calculations and display. If all Date objects you use are set to the same time of the day, then you can safely ignore the effect of the time component in your comparisons. If you look carefully, the time component of your Date object is set to midnight.

Upvotes: 0

verdesmarald
verdesmarald

Reputation: 11866

As others have pointed out, you should probably store your dates as dates, not strings; nevertheless...

If you want to turn a Date back into a string in that format you can use the following:

DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date();
String dateStr = formatter.format(date); // Gives "22-May-11"

If you need MAY instead of May, just use toUpperCase() on the resultant string.

Upvotes: 0

tofutim
tofutim

Reputation: 23374

You can use java.text.DateFormat (actually SimpleDateFormat) to get you where you want to go, but maybe you shouldn't be storing the dates as strings in your database. It will do output and parsing.

SimpleDateFormat sdf =
            new SimpleDateFormat("DD-MMM-YY");
Date parsed = sdf.parse(dateString);

See http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/

Once you get the Date, you can turn it into the format you want but it will be held in memory as a Date object. You can get it in the form you want using

String dateString = sdf.format(parsed);

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240900

DateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
Date d = sdf.parse("18-NOV-10");

Upvotes: 0

Related Questions