From java.util.Date, What is the easiest/smart way to find out if it's the first day of a month ?
Asked
Active
Viewed 81 times
-1
-
It'd be helpful If you tell us what you have already tried? – Abubakr Dar May 21 '15 at 05:11
-
Use Java 8s time api or Joda time – MadProgrammer May 21 '15 at 05:14
-
possible duplicate of [First day of next month with java Joda-Time](http://stackoverflow.com/questions/4786169/first-day-of-next-month-with-java-joda-time) – Basil Bourque May 21 '15 at 07:10
3 Answers
1
With the "classic" Java API (pre Java 8):
public static boolean isFirstDayOfMonth(final Date date)
{
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int dom = cal.get(Calendar.DAY_OF_MONTH);
return dom == 1;
}
Then you just call it like this:
isFirstDayOfMonth(new Date());

Burkhard
- 14,596
- 22
- 87
- 108
0
Calendar
class is better for such things.
But if you really want to do this with Date
only, then
Date d = new Date();
d = new Date(d.getYear(), d.getMonth(), 0);
switch (d.getDay()) {
case 0: System.out.println("Monday");
break;
case 1: System.out.println("Tuesday");
break;
case 2: System.out.println("Wednessday");
break;
case 3: System.out.println("Thusrday");
break;
case 4: System.out.println("Friday");
break;
case 5: System.out.println("Satureday");
break;
case 6: System.out.println("Sunday");
break;
}

Soumitri Pattnaik
- 3,246
- 4
- 24
- 42
0
Java 8
Date date = new Date();
Instant instant = date.toInstant();
int dom = LocalDateTime.
ofInstant(instant, ZoneId.systemDefault()).
getDayOfMonth();
System.out.println(dom);
Joda Time (Pre Java 8)
Date date = new Date();
int dom = LocalDateTime.fromDateFields(date).getDayOfMonth();
System.out.println(dom);

MadProgrammer
- 343,457
- 22
- 230
- 366