// 月份只差其实就是,年份只差 乘以12 然后再加上 月份只差, 比如 2009-09 ----2012-02
// 这个就应该 (2012-2009 )*12 + (2-9)=36 +(-7)=29
//思路有了直接使用java套就可以了
public static void main(String[] args) throws ParseException {
//字符串格式化
DateFormat df = new SimpleDateFormat("yyyy-MM")
//字符串装换为Calendar
Calendar c= Calendar.getInstance()
c.setTime(df.parse("2009-01"))
//字符串装换为Calendar
Calendar d= Calendar.getInstance()
d.setTime(df.parse("2012-01"))
//计算年份只差 乘以12 然后加上月份之差
int m=(d.get(Calendar.YEAR)-c.get(Calendar.YEAR))*12+d.get(Calendar.MONTH)-c.get(Calendar.MONTH)
System.out.println(m)
}
//建议楼主多看看api,现在网上有很多西方下载就不给你连接了。
按照你的要求,如何得到一个月有多少天,这里并没有说是什么年份,所以默认当年(不同年份的月份天数可能不一样,例如闰年的二月)
因此问题变为
输入条件:指定某一个月
输出结果:当年这个月份的天数
思路:在Java8里新的时间API里,月份已经被抽象成了枚举Month,所以可以把输入条件定义为枚举类型的Month,然后获取当前时间X,把时间X的月份修改为输入条件的月份,此时时间X变为X1,根据本身提供的方法lengthOfMonth就可以直接得到X1所在当月的天数了
代码:(请将JDK升到8)
public static void main(String[] args) {System.out.println(countDaysInMonth(Month.MAY))
}
public static int countDaysInMonth(Month month){
// 获取当前时间
LocalDate now = LocalDate.now()
System.out.println(now)
// 把当前时间的月份修改为输入的月份
LocalDate thisMonthDate = now.withMonth(month.getValue())
System.out.println(thisMonthDate)
return thisMonthDate.lengthOfMonth()
}
也可以连着写,更美观点
public static int countDaysInMonth(Month month){return LocalDate.now()
.withMonth(month.getValue())
.lengthOfMonth()
}
非常直观且易懂好用,在Java8里with就代表着修改意思,withMonth那就是修改月份,所以整个代码读下来就变成
获取当前时间A
修改A的月份为输入条件得到时间B
计算B所在月的天数
天数好算,月数不好算,因为有28天,30天,31天,偶尔还有29天一个月的,告诉你怎么算天数吧public static java.util.Date toDate(String dateStr) {
Date d=null
SimpleDateFormat formater=new SimpleDateFormat("yyyy/MM/dd")
try {
formater.setLenient(false)
d=formater.parse(dateStr)
} catch(Exception e) {
d=null
}
return d
}
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000
}
public static void main(String[] args) {
System.out.println("请输开始日期如:2013/03/15")
Scanner sc=new Scanner(System.in)
String dateStr1=sc.nextLine()
Date date1=toDate(dateStr1)
System.out.println("请输结束日期如:2013/03/15")
String dateStr2=sc.nextLine()
Date date2=toDate(dateStr2)
Long day=dayDiff(date1,date2)
System.out.println("相差"+day+"天")
}