java 里时间对比

1、取得指定日期是星期几
取得指定日期是星期几可以采用下面两种方式取得日期是星期几:
a、使用Calendar类
//根据日期取得星期几
public static String getWeek(Date date){
String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if(week_index<0){
week_index = 0;
} 
return weeks[week_index];
}


b、使用SimpleDateFormat类
//根据日期取得星期几
public static String getWeek(Date date){ 
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String week = sdf.format(date);
return week;
}


注:格式化字符串存在区分大小写
对于创建SimpleDateFormat传入的参数:EEEE代表星期,如“星期四”;MMMM代表中文月份,如“十一月”


;MM代表月份,如“11”;
yyyy代表年份,如“2010”;dd代表天,如“25” 
2、取得日期是某年的第几周
根据日期入得日期是某年的第几周。
//取得日期是某年的第几周
public static int getWeekOfYear(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_of_year = cal.get(Calendar.WEEK_OF_YEAR);
return week_of_year;
}


3、得到某年的某个月有多少天
已知年份和月份,取得该月有多少天。
//取得某个月有多少天
public static int getDaysOfMonth(int year,int month){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month-1);
int days_of_month = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
return days_of_month;
}


4、取得两个日期之间的相差多少天
已知两个日期,计算它们之间相差多少天。
// 取得两个日期之间的相差多少天
<pre name="code" class="html">public static long getDaysBetween(Date date0, Date date1) {
long daysBetween = (date0.getTime() - date1.getTime() + 1000000) / 86400000;// 86400000=3600*24*1000 用立即数,减少乘法计算的开销
return daysBetween;
}


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值