Skip to content Skip to sidebar Skip to footer

Convert Date To Year And Month

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date. My Date is Like - 29/03/2017. I want to c

Solution 1:

You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.

example

LocalDate dob =new LocalDate(1992, 12, 30);
        LocalDate date=new LocalDate(2010, 12, 29);

        Periodperiod=newPeriod(dob, date, PeriodType.yearMonthDay());
        System.out.println(period.getYears() + " years and " +
                           period.getMonths() + " months");

Solution 2:

I found my answer using Calender class .

First i find the difference between two days and using that days i found the years and months.

Here i post my code, which i think help to others.

int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;

getDateDiffString() Method. In this method we need to pass end date

publicstatic String getDateDiffString(String endDate)
    {
        try
        {
            Calendarcal= Calendar.getInstance();

            SimpleDateFormatdateFormat=newSimpleDateFormat("dd/MM/yyyy");
            DatedateTwo= dateFormat.parse(endDate); 

            longtimeOne= cal.getTimeInMillis();
            longtimeTwo= dateTwo.getTime();
            longoneDay=1000 * 60 * 60 * 24;
            longdelta= (timeTwo - timeOne) / oneDay;

            if (delta > 0) {
                return"" + delta + "";
            }
            else {
                delta *= -1;
                return"" + delta + "";
            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        return"";
    }

Solution 3:

if your date's format is fixed, you can do it like this :

String myDate = "29/03/2017";

String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)

Solution 4:

this method to convert the normal string to date format

StringcurrentDateString="02/27/2012 17:00:00";
SimpleDateFormatsd=newSimpleDateFormat("mm/dd/yyyy HH:mm:ss");
DatecurrentDate= sd.parse(currentDateString);

after that you get the formal method

Solution 5:

You Should use SimpleDateFormate !

For Example:--- You can get time & Date as you want:-

Dateemail_date= m.getSentDate();// this is date which you are gettingDateFormatdate=newSimpleDateFormat("EEE MMM yyyy");
            DateFormattime=newSimpleDateFormat("hh:mm aa");
            String date_str=date.format(email_date);
            String time_str=time.format(email_date);

Post a Comment for "Convert Date To Year And Month"