[java] How to get day of the month?

I am trying to retrieve which day of the month it is.

Such as today is August 29,2011.

What i would like to do is just get the days number such as 29, or 30. Which ever day of the month it is.

How would i go about doing this?

This question is related to java android

The answer is


tl;dr

LocalDate           // Represent a date-only, without time-of-day and without time zone.
.now()              // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth()    // Interrogate for the day of the month (1-31). 

java.time

The modern approach is the LocalDate class to represent a date-only value.

A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.

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

You can also get the day-of-week.

DayOfWeek dow = ld.getDayOfWeek();

About java.time

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

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

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

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

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.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.

Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.

Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();

Or use similar code with the LocalDate class that has no time-of-day portion.


It is simplified a lot in version Java 8. I have given some util methods below.

To get the day of the month in the format of int for the given day, month, and year.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfMonth());
        return LocalDate.of(year, month, day).getDayOfMonth();
    }

To get current day of the month in the format of int.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth();
    }

To get the day of the week in the format of String for the given day, month, and year.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfWeek());
        return LocalDate.of(year, month, day).getDayOfWeek().toString();
    }

To get current day of the week in the format of String.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata"))..getDayOfWeek());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfWeek().toString();
    }

Take a look at GregorianCalendar, something like:

final Calendar now = GregorianCalendar.getInstance()
final int dayNumber = now.get(Calendar.DAY_OF_MONTH);

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(aDate);
    return cal.get(Calendar.DAY_OF_MONTH);
}

//This will get you the day of the month
String.valueOf((Calendar.getInstance()).get(Calendar.DAY_OF_MONTH))

You could start by reading the documentation for Date. Then you realize that Date’s methods are all deprecated and turn to Calender instead.

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.DAY_OF_MONTH));

Java 8 Update

Java 8 introduces the following packages for time and date manipulation.

java.time.*;
java.time.format.*;

java.time.chono.*;    
java.time.temporal.*;
java.time.zone.*;

These are more organized and intuitive.

We need only top two packages for the discussion.
There are 3 top level classes - LocalDate, LocalTime, LocalDateTime for describing Date, Time and DateTime respectively. Although, they are formatted properly in toString(), each class has format method which accepts DateTimeFormatter to format in customized way.

DateTimeFormatter can also be used show the date given a day. It has few

import java.time.*;
import java.time.format.*;

class DateTimeDemo{
    public static void main(String...args){
        LocalDateTime x = LocalDateTime.now();
        System.out.println(x.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));//Shows Day and Date.

        System.out.println(x.format(DateTimeFormatter.ofPattern("EE")));//Short Form
        System.out.println(x.format(DateTimeFormatter.ofPattern("EEEE")));//Long Form

    }
}

ofLocalizedTime accepts FormatStyle which is an enumeration in java.time.format

ofPattern accepts String with restricted pattern characters of restricted length. Here are the characters which can be passed into the toPattern method.

enter image description here

You can try different number of patterns to see how the output will be.

Check out more about Java 8 DateTime API here


LocalDate date = new Date(); date.lengthOfMonth()

or

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");

DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");

String stringDate = formatter.format(date);

String month = monthFormatter.format(date);