java,calander,date时间常用方法

    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]; 
    } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值