simple date conversion

Hi There,

How to convert yyyy-mm-dd hh:mm:ss.sss to only yyyy as a String.

i.e: my value in DB of type datetime, 2009-11-04 00:00:00.0 to 2009 as a String.

Thanks.
thearthaAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Well you could do a substring then ;)
0
 
CEHJCommented:
Simplest would be
String d = String.format("%tY", resultSet.getDate(someCol));

Open in new window

0
 
thearthaAuthor Commented:
@CEHJ:

what if the date is not coming from resultSet, but just as String?
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
for_yanCommented:

I do it this way:

select to_char(date_col_name,'YYYY') from table

  String dateString = resultSet.getString(1)

Works with Orcale, don't know if it works with other databases
0
 
thearthaAuthor Commented:
Thanks CEHJ....
0
 
CEHJCommented:
:)
0
 
for_yanCommented:


If it comes just as String, you can use SimpleDateFormat

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat f1 = new SimpleDateFormat("yyyy");

java.util.Date dd = f.parse(dateString, new ParsePosition(0));

String newString = f1.format(dd);

Substring is of course simpler :)




 
0
 
objectsCommented:
use of substring is error prone, best to use SimpleDateFormat as for_yan suggested above to parse the date string, then format it as a string as required
0
 
CEHJCommented:
>>use of substring is error prone

In what way?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.