public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
Calendar now = Calendar.getInstance();
int year=now.get(Calendar.YEAR);
int month=now.get(Calendar.MONTH) + 1;
int day=now.get(Calendar.DAY_OF_MONTH);
Calendar nowDate = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//'2010-08-10'这是自己输入的需要计算的年月日
nowDate.setTime(sdf.parse(Integer.toString(year)+"-"+Integer.toString(month)+"-01"));
/*因为它返回的是一个整型(1~7),1代表星期日,以此类推,7代表星期六。*/
int dayone = nowDate.get(Calendar.DAY_OF_WEEK)-1;
int week=now.get(Calendar.DAY_OF_WEEK);
int monthDay=getDaysOfMonth(year, 9);
System.out.println("当年: " + year);
System.out.println("当月: " + month);
System.out.println("今天: " + day+ "号");
System.out.println("今天周: " + (week-1));
System.out.println("本月第一天为周: "+dayone);
System.out.println("该月天数为: "+monthDay);
System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
System.out.println("分: " + now.get(Calendar.MINUTE));
System.out.println("秒: " + now.get(Calendar.SECOND));
System.out.println("当前时间毫秒数:" + now.getTimeInMillis());
System.out.println(now.getTime());
Date d = new Date();
System.out.println(d);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateNowStr = sdf1.format(d);
System.out.println("格式化后的日期:" + dateNowStr);
String str = "2012-1-13 17:26:33"; //要跟上面sdf定义的格式一样
Date today = sdf.parse(str);
System.out.println("字符串转成日期:" + today);
}
/**
* 取得指定年份,月份的最后一天,最容易理解
* 其实就是判断闰年问题:能被4整除,但不能被100整除,除非能被400整除
* */
public static int getDaysOfMonth(int year,int month){
int days[]={31,31,28,31,30,31,30,31,31,30,31,30,31};
if(2==month && 0==(year%4) && (0!=(year%100) || 0==(year%400))){
//判断闰年,当 month=2 时才判断,以减少计算量
days[2]=29;
}
return days[month];
}
java,calander,date时间常用方法
最新推荐文章于 2023-11-23 00:13:48 发布