Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Month, Day and Year values from a String using Java

Tags:

java

string

date

How to extract Day, Month and Year values from a string [like 18/08/2012]. I tried using SimpleDateFormat, but it returns a Date object and I observed that all the Get methods are deprecated. Is there any better way to do this?

Thanks

like image 359
usp Avatar asked Aug 20 '12 17:08

usp


2 Answers

Personally I'd use Joda Time, which makes life considerably simpler. In particular, it means you don't need to worry about the time zone of the Calendar vs the time zone of a SimpleDateFormat - you can just parse to a LocalDate, which is what the data really shows you. It also means you don't need to worry about months being 0-based :)

Joda Time makes many date/time operations much more pleasant.

import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;

public class Test {

    public static void main(String[] args) throws Exception {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy")
            .withLocale(Locale.UK);

        LocalDate date = formatter.parseLocalDate("18/08/2012");

        System.out.println(date.getYear());  // 2012
        System.out.println(date.getMonthOfYear()); // 8
        System.out.println(date.getDayOfMonth());   // 18
    }
}
like image 189
Jon Skeet Avatar answered Oct 08 '22 06:10

Jon Skeet


Simply go for String.split(),

String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
..... and so on
like image 35
jayantS Avatar answered Oct 08 '22 06:10

jayantS