简体   繁体   中英

Get date , month and year from particular date

I want to get the date , month and year from the particular date.

I have used below code :

 String dob = "01/08/1990";

        int month = 0, dd = 0, yer = 0;

        try {

            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            Date d = sdf.parse(dob);
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            month = cal.get(Calendar.MONTH);
            dd = cal.get(Calendar.DATE);
            yer = cal.get(Calendar.YEAR);

        } catch (Exception e) {
            e.printStackTrace();
        }

So from the above code i am getting month -0 , yer - 1990 and date - 8

But i want month - 01 , date - 08 and yer - 1990 .

I have defined the date format also but i am not getting perfect value from date, month and year.

Month in calendar will be from 0-11. You have to add +1 in month.

String dob = "01/08/1990";
String month = 0, dd = 0, yer = 0;
try {
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
     Date d = sdf.parse(dob);
     Calendar cal = Calendar.getInstance();
     cal.setTime(d);
     month = checkDigit(cal.get(Calendar.MONTH)+1);
     dd = checkDigit(cal.get(Calendar.DATE));
     yer = checkDigit(cal.get(Calendar.YEAR));

} catch (Exception e) {
     e.printStackTrace();
}

checkDigit method for adding preceeding zero. checkDigit() method returns String value. if You want to convert in integer then you can do like Integer.parseInt(YOUR_STRING);

// ADDS 0  e.g - 02 instead of 2
    public String checkDigit (int number) {
        return number <= 9 ? "0" + number : String.valueOf(number);
    }
public static void main (String[] args) throws java.lang.Exception
{
     String dob = "01/08/1990";

    int month = 0, dd = 0, yer = 0;

    try {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date d = sdf.parse(dob);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        month = cal.get(Calendar.MONTH);
        dd = cal.get(Calendar.DATE);
        yer = cal.get(Calendar.YEAR);

        System.out.println("Month - " + String.format("%02d", (month+1)));
        System.out.println("Day - " + String.format("%02d", dd));
        System.out.println("Year - " + yer);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Since months in the Calendar are considered from 0-11 so we need to add 1 to it.

I have executed a sample you can check here

In java.util.Calendar month is zero based, so it gives you correct values.

Check the constants in the Calendar class:

public final static int JANUARY = 0;
public final static int FEBRUARY = 1;
...
public final static int DECEMBER = 11;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM