aspose file tools*
The moose likes Java in General and the fly likes Extracting year in MM/dd/yyyy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Extracting year in MM/dd/yyyy" Watch "Extracting year in MM/dd/yyyy" New topic
Author

Extracting year in MM/dd/yyyy

Venkat Babu
Ranch Hand

Joined: Jan 12, 2007
Posts: 47
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

Joined: Aug 16, 2005
Posts: 14269
    
  21

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(...).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Venkat Babu
Ranch Hand

Joined: Jan 12, 2007
Posts: 47
Thanks for your input.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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 good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Extracting year in MM/dd/yyyy