本帖最后由 hyz123456 于 2013-10-6 15:39 编辑
看了毕老师的视频,自己写了一个代码,可以判断从今天到某一指定日期共有多少天,并且能算出这中间有多少天是周末,上班族学生党必备啊!激动有米有!
/*
需求:
写一个代码,计算从X月X号到X月X号共几天weekday
思路:
获取当前时间段,获取终止时间,循环将日期加1,当获取的星期为weekday时,count++;
*/
import java.util.*;
import java.text.*;
import static java.util.Calendar.*;
class CalendarDemo
{
public static void main(String[] args)
{
System.out.println("请输入终止时间yyyy-mm-dd");
Scanner sc = new Scanner(System.in);
String date = sc.next();
String[] week = {" ","星期日","星期一","星期二",
"星期三","星期四","星期五","星期六"};//数组用来查星期
//String date = "2016-2-29";
Calendar c = Calendar.getInstance();
int Y = c.get(Calendar.YEAR); //获取当前年份
int M = c.get(Calendar.MONTH); //获取当前月份
int D = c.get(Calendar.DAY_OF_MONTH); //获取当前日期
sop("起始日期:"+Y+"年"+(M+1)+"月"+D+"日");
int[] in = new Tool().getNum(date);
//将输入的日期字符串处理获取年份,月份,日期,并将其装入数组中....
int endY = in[0]; //获取结束年份
int endM = in[1]-1; //获取结束月份
int endD = in[2]; //获取结束日期
int times=0; //计数器
int day=0;
for (;!(Y>endY||(Y==endY&M>endM)||(Y==endY&M==endM&D>endD));day++)
{
String weekName = week[c.get(DAY_OF_WEEK)];
if(weekName.compareTo("星期日")==0||weekName.compareTo("星期六")==0)
times+=1;
c.add(Calendar.DAY_OF_MONTH,1); //将当前日期+1
Y=c.get(YEAR);
M=c.get(MONTH);
D=c.get(DAY_OF_MONTH);
}
if (times==0)
throw new RuntimeException("岁月匆匆,少年你就不要再纠缠了,咱得往前看.....");
sop("终止日期:"+endY+"年"+(endM+1)+"月"+endD+"日");
sop("加上今天一共有:"+day+"天");
sop("周末一共有:"+times+"天");
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Tool
{
public static int[] getNum(String s)
{ //用以获取输入日期所对应的Int值,有点复杂待改进...
String str = "0123456789"; //运用查表法转换int...
int[] i = new int[3];
int count=0;
int num=0;
for (int x =0;x<s.length() ;x++ )//用以判断输入的字符串格式是否正确
{
char ch = s.charAt(x);
if (ch=='-') //当读到'-'时,将前面的字符封装成数组内一个对象
{
i[count]=num;
count++;
num=0;
}
else if(ch>='0'&ch<='9')
{
num=num*10;
int key = str.indexOf(ch);
num+=key;
}
else throw new RuntimeException("撸多了吧?您输入格式或数字有误!");
}
i[count]=num; //因为后面没有'-'了。手动将Day值赋予i[2];
int[] month = {29,31,28,31,30,31,30,31,31,30,31,30,31,};
if (i[1]<=12) //用查表法判断月份所对应的天数是否正确
{
if (i[1]==2&&i[0]%4==0)
{
if (i[2]<=month[0])
return i;
}
if (i[2]<=month[i[1]])
return i;
}
throw new RuntimeException("输入日期不存在!难道你的数学是体育老师教的?");
}
}
代码不是很完善,望大家多提提意见.....
|