Adham
Adham

Reputation: 64844

Why getting the wrong day in month using Android Java?

Where the day today is Oct 24, 2011 .

but using this code

  Calendar currentDate = Calendar.getInstance();
  int d = currentDate.DAY_OF_MONTH;

gives me the date 5

P.S. the date in emulator settings is October 24, 2011

Upvotes: 2

Views: 1681

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338516

ZonedDateTime

The modern way to do this is with the java.time classes.

A ZonedDateTime represents a moment on the timeline with a resolution of nanoseconds.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
int dayOfMonth = zdt.getDayOfMonth();

About java.time

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

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

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

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

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.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

 currentDate.DAY_OF_MONTH; 

is constant which is used internally in Calendar class. To get the current day of month use

use

currentDate.get(Calendar.DAY_OF_MONTH);

Update:

how to shift the current date 6 days, and get the new day and month value ? //adding 6 days currentDate.add(Calendar.DATE, 6);

//retrieving the month now, note month starts from 0-Jan, 1-Feb
currentDate.get(Calendar.MONTH);

Upvotes: 12

nhaarman
nhaarman

Reputation: 100388

The DAY_OF_MONTH field is a constant Integer. Use the method get instead:

currentDate.get(Calendar.DAY_OF_MONTH);

You can add for example 6 days using:

currentDate.add(Calendar.DAY_OF_MONTH, 6);

See also this page.

Upvotes: 4

Related Questions