• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Extracting year in MM/dd/yyyy  RSS feed

 
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
 
Java Cowboy
Posts: 16084
88
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.
 
(instanceof Sidekick)
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.
 
A berm makes a great wind break. And Iwe all like to break wind once in a while. Like this tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!