user3547706
user3547706

Reputation:

Issue in convert calendar object to date android

I want to convert calendar object to date as follow.

int year,month,day;
mCalendarEnd = Calendar.getInstance();
year = mCalendarEnd.get(Calendar.YEAR);
month = mCalendarEnd.get(Calendar.MONTH)+1;
day   = mCalendarEnd.get(Calendar.DAY_OF_MONTH);

Now convert it to date object

Date d1 = new Date(day,month,year);

when I print date object:

System.out.println("Date : "+d1.getDay()+"/"+d1.getMonth()+"/"+d1.getYear());

it should print current date but in above code it prints the wrong date. Any idea how can I solve this problem? your all suggestion are appreciable.

Upvotes: 3

Views: 11976

Answers (5)

Alireza Noorali
Alireza Noorali

Reputation: 3265

calendar.getTime() returns Date object.

but if you just need today date new Date() returns today date as Date object, too.

Calendar example:

Calendar calendar = Calendar.getInstance()
Log.i("My Tag", "calendar getTime -----> " + calendar.getTime());

Output:

My Tag: calendar getTime -----> Wed Dec 05 13:03:43 GMT+03:30 2018

Date Example:

Log.i("My Tag", "new Date -----> " + new Date());

Output:

My Tag: new Date -----> Wed Dec 05 13:05:38 GMT+03:30 2018

as you see both of them have the same output.

Upvotes: 3

Bhushan
Bhushan

Reputation: 205

You need to do it like this

    //Set calendar
    Calendar calendar = Calendar.getInstance();
    Date date1 = calendar.getTime(); // gives a date object

    //To get day difference, Just an example
    calendar.add(Calendar.DAY_OF_MONTH, -7);
    Date date2 = calendar.getTime(); // gives a date object

    long differenceInMillis = Date1.getTime() - Date2.getTime();
    long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);

Or No need of date objects

    Calendar calendar = Calendar.getInstance();
    long date1InMillis = calendar.getTimeInMillis();

    calendar.add(Calendar.DAY_OF_MONTH, -7);
    long date2InMillis = calendar.getTimeInMillis();

    long differenceInMillis = date1InMillis - date2InMillis;
    long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
    calendar.getTimeInMillis()

Upvotes: 3

Naveen Kumar
Naveen Kumar

Reputation: 11

Put this in your code:

Date d1 = new Date(year, month, day);
System.out.println("Date : " + d1.getDate() + "/" +d1.getMonth() + "/" + d1.getYear());

you will get the correct date.

Upvotes: 1

balu b
balu b

Reputation: 272

d1=new Date(year, month, day);
System.out.println("Dt:"+d1.getDate()+"/"+d1.getMonth()+"/"+d1.getYear());

Upvotes: 0

keronconk
keronconk

Reputation: 359

Why you don't use just the calendar?

System.out.println("Date   : " + day + "/" + month + "/" + year);

result 1/1/1900

or you want other format? but dont increment the month with 1

System.out.println("Date   : " + day + "/" + new DateFormatSymbols().getMonths()[month] + "/" + year);

result 1/January/1900

Upvotes: 1

Related Questions