How can Joda or Java returns true if day is the first day of the month? [duplicate]

风流意气都作罢 提交于 2019-12-25 05:11:45

问题


How in Joda or Java can I write a method that returns a boolean value if today is the first day of the current month? Like if today's date is the first day of this month, it will return true.

It could be something like this:

public static boolean isFirstDayOfTheMonth( Date dateToday ){
boolean isFirstDay = false;
//code to check if dateToday is first day of the current month.
returns isFirstDay;
}

Thank you in advance!


回答1:


LocalDate::getDayOfMonth

With Java SE 8 and later, call LocalDate::getDayOfMonth.

public static boolean isFirstDayOfTheMonth(LocalDate dateToday ){
  return dateToday.getDayOfMonth() == 1;
}



回答2:


Using Joda-time

public static boolean isFirstDayOfTheMonth( DateTime dateToday ){
returns dateToday.dayOfMonth().get()==1
}



回答3:


This code gives you the result you need.

public static boolean isFirstDayOfTheMonth(Date dateToday){
  Calendar c = new GregorianCalendar();
  c.setTime(dateToday );
  if (c.get(Calendar.DAY_OF_MONTH) == 1) {
    return true;
  }
  returns false;
}



回答4:


Use this with a normal java Date:

public static boolean isFirstDayOfTheMonth( Date dateToday ){
     if(dateToday.getDate() == 1){
        System.out.println("First of the month");
        return true;
    }else{
        return false';
    }

}

I hope this helps. And good luck with the rest of your code.




回答5:


Do not use the Date class, it has deprecated methods. Calendar is better.

public boolean isFirstDayOfMonth(Calendar calendar)
{
    return calendar.get(Calendar.DAY_OF_MONTH) == 1;
}

Example method call:

isFirstDayOfMonth(Calendar.getInstance());


来源:https://stackoverflow.com/questions/24451419/how-can-joda-or-java-returns-true-if-day-is-the-first-day-of-the-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!