开发者

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"


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);


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜