2

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

Adham
  • 63,550
  • 98
  • 229
  • 344

3 Answers3

12
 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);
jmj
  • 237,923
  • 42
  • 401
  • 438
  • that's it. thanks, I will accept your question soon, another question how to shift the current date 6 days, and get the new day and month value ? – Adham Oct 24 '11 at 12:35
4

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.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
0

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.

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