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.
//This will get you the day of the month
String.valueOf((Calendar.getInstance()).get(Calendar.DAY_OF_MONTH))
You'll want to do get a Calendar instance and get it's day of month
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
You can also get DAY_OF_WEEK, DAY_OF_YEAR, DAY_OF_WEEK_IN_MONTH, etc.
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);
Take a look at GregorianCalendar, something like:
final Calendar now = GregorianCalendar.getInstance()
final int dayNumber = now.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.
You can try different number of patterns to see how the output will be.
Check out more about Java 8 DateTime API here