• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Extracting year in MM/dd/yyyy

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your input.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic