16

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

usp
  • 797
  • 3
  • 10
  • 24

8 Answers8

22

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
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @LuisAlfredoSerranoDíaz: Well yes, you'd have to use the Joda Time library, putting it on the classpath. These days I'd suggest using java.time instead though, which *is* part of the standard library. – Jon Skeet Sep 29 '19 at 11:56
17

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
jayantS
  • 817
  • 13
  • 29
9

This should get you going without adding external jars

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");  
Date parse = sdf.parse("18/08/2012");  
Calendar c = Calendar.getInstance();  
c.setTime(parse);  
System.out.println(c.get(Calendar.MONTH) + c.get(Calendar.DATE) + c.get(Calendar.YEAR)); 
Linh
  • 57,942
  • 23
  • 262
  • 279
Srujan Kumar Gulla
  • 5,721
  • 9
  • 48
  • 78
6

tl;dr

java.time.LocalDate.parse(
    "18/08/2012" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
).getDayOfMonth​() // .getYear​() .getMonth()

java.time

The modern approach uses the java.time classes. Avoid the troublesome legacy classes such as Date & Calendar.

LocalDate

String input = "18/08/2012" ;

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

ld.toString(): 2012-08-18

Getter methods

Interrogate for the parts.

int d = ld.getDayOfMonth​() ;
int m = ld.getMonthValue() ;
int y = ld.getYear() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
5

Create a java.util.Calendar object out of that date as follows and extract the date parts:

Calendar cal = Calendar.getInstance();
cal.setTime(<date from simple-date-format).
cal.get(Calendar.MONTH);

etc.,

Vikdor
  • 23,934
  • 10
  • 61
  • 84
  • 2
    Note that this means you've got to make sure the `SimpleDateFormat` and the `Calendar` use the same time zone, as otherwise you'll get the wrong values. Better to stick to types which *only* deal with dates, IMO. – Jon Skeet Aug 20 '12 at 17:48
  • Thanks @JonSkeet, I didn't realize the timezone issue until I saw your response referring to JodaTime. – Vikdor Aug 20 '12 at 17:52
2

Another approach may be use Calendar object get(Calendar.MONT)

Example:

Calendar cal = Calendar.getInstance();
cal.setTime(dateObj).
cal.get(Calendar.MONTH);

(or)

You may use String.split() also.

kosa
  • 65,990
  • 13
  • 130
  • 167
2

Use This And Pass the date Value

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
Date parse = sdf.parse("18/01/2018");
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
int date = calendar.get(Calendar.DATE);
//+1 Is Important Because if the month is January then coming 0 so Add +1
int month = calendar.get(Calendar.MONTH)+1;
int year = calendar.get(Calendar.YEAR);
System.out.println("Date:"+date +":Month:"+ month + ":Year:"+year);
abby
  • 350
  • 4
  • 21
  • While using `SimpleDateFormat`, `Date` and `Calendar` was a reasonable answer when this question was asked 6 years ago, those classes are now long outdated, and `SimpleDateFormat` in particular was always troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jun 27 '18 at 14:02
  • Now a days also more number of project is using Lower Version & maximum people are not using java 1.8. People who are using JDK 8 in project this people can happily use Java.time Package – Abhijit Patra Aug 24 '18 at 09:20
  • There’s certainly room for an answer using the outdated and poorly designed classes too, and thanks for contributing one. I just wanted to make clear that this is what it is. Also if upgrading to Java 8 or later is not an option yet, one may still add [the ThreeTen Backport library](https://www.threeten.org/threetenbp/) to one’s project and use java.time through it. – Ole V.V. Aug 24 '18 at 09:23
1

In it the String is stored in an array in form of elements, and with the help of split() function, I have separated it and retrieved it from the array str[] and stored in 3 different variables day, month & year.

import java.util.*;

public class date {

    public static void main(String[] args) throws Exception {
        String str[] = "18/08/2012".split("/");
        int day = Integer.parseInt(str[0]);
        int month = Integer.parseInt(str[1]);
        int year = Integer.parseInt(str[2]);
        System.out.println(day);
        System.out.println(month);
        System.out.println(year);
    }
}