Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Extracting year in MM/dd/yyyy

 
Venkat Babu
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In a string i have "01/02/2002", i want to extract the year part.
Probably I can just use substring and extract year.

But I am doing this, just wanted to know is this right? Seems unnecessary.


String strDate = "01/02/2002";
DecimalFormat fmt100 = new DecimalFormat("0000");
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar _calender = Calendar.getInstance();
Date parsed = format.parse(strDate);

_calender.setTime(parsed);
System.out.println (fmt100.format(_calender.get(Calendar.YEAR))); //prints 2002
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are sure the format is going to be MM/dd/yyyy and you don't need to check if the string really contains a string in this format, then just using substring is the quickest and shortest way to do it.

If you need the year in an int, then ofcourse you can parse it using Integer.parseInt(...).
 
Venkat Babu
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your input.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java 1.3 one test I conducted showed substringing around 100x faster than parsing a date and going back toString() in another format. Unless you have thousands of these in the code path while the user is waiting for results, they'd never notice that time difference though.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic