然后,我们调用lengthOfMonth()方法来获取该月份的天数。 接下来,我们可以编写一个简单的示例程序来测试这个方法: publicclassMain{publicstaticvoidmain(String[]args){intyear=2022;intmonth=6;intdaysInMonth=getDaysInMonth(year,month);System.out.println("Days in month: "+daysInMonth);}publicstaticintgetDaysInM...
还可以用这个类得到 当月共有多少天,YearMonth 实例的 lengthOfMonth() 方法可以返回当月的天数,在判断 2 月有 28 天还是 29 天时非常有用。 1YearMonth currentYearMonth = YearMonth.now(); 2System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth()); ...
public static int countDaysInMonth(Month month){ return LocalDate.now() .withMonth(month.getValue()) .lengthOfMonth();}非常直观且易懂好用,在Java8里with就代表着修改意思,withMonth那就是修改月份,所以整个代码读下来就变成 获取当前时间A 修改A的月份为输入条件得到时间B 计算B所...
YearMonthcurrentYearMonth=YearMonth.now(); System.out.printf("Days in month year %s: %d%n",currentYearMonth,currentYearMonth.lengthOfMonth()); YearMonthcreditCardExpiry=YearMonth.of(2019,Month.FEBRUARY); System.out.printf("Your credit card expires on %s %n",creditCardExpiry); } } D...
cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天 lastDay = format.format(cale.getTime()); System.out.println("---2---lastDay:"+lastDay); //获取当前月第一天: Calendar c = Calendar.getInstance(); c.add(
6 int day = today.getDayOfMonth(); 7 8 System.out.printf("Year : %d Month : %d day : %d t %n", year, month, day); 9 } 3.处理特定日期 在第一个例子里,我们通过静态工厂方法now()非常容易地创建了当天日期。我们还可以调用另一个有用的工厂方法 LocalDate.of() 创建任意日期, 该方法需...
import java.util.Scanner;public class E { public static void main(String[] args) { int y,m,d,days,i,d1=0;System.out.printf("请输入年,月,日:\n");Scanner in=new Scanner(System.in);y=in.nextInt();Scanner in1=new Scanner(System.in);m=in1.nextInt();Scanner in2=...
int doy = calendar.get(Calendar.DAY_OF_YEAR); // Calendar.DAY_OF_WEEK 在这一周 的这一天,从星期日当第一天从1开始算的,所以会是 +1 int dow = calendar.get(Calendar.DAY_OF_WEEK); // Calendar.DAY_OF_WEEK_IN_MONTH 在这一个月 这一天在 第几周 ...
get(Calendar.DAY_OF_MONTH); System.out.println(i1); System.out.println(i2); // 3 26 setTime 代码语言:javascript 复制 //设置时间,传入Date类型 instance.setTime(new Date()); set 代码语言:javascript 复制 //设置时间,通过Calendar常量 instance.set(Calendar.YEAR,2019); instance.set(Calendar....
DayOfWeek枚举类用来表示一个周的七天。常用的方法和Month枚举类的几乎一致,包括of(int dayOfWeek)静态方法用于创建DayOfWeek对象;getValue()方法用来获取该对象的值;plus(long days)和minus(long days)方法用来进行加减法计算。也可以使用getDisplayName(TextStyle style, Locale locale)来格式化输出。代码演示如下: ...