时间操作

2018-08-15  本文已影响0人  小灰灰_5c75

//获取某年2月份天数

       @Test

       public voidTest3() throwsParseException {

           Scannersc = new Scanner(System.in);

           System.out.print("请输入年数:");

           int year= sc.nextInt();

           Datedate = new Date();

           System.out.println("当前日期:"+date);

           {

              //字符串拼接后格式化

              Stringd1 = year+"-03-01";

              SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");

              Dated2 = sdf.parse(d1);

              System.out.println("格式化日期后:"+d2);

           }

           //输入年份,找到3月-1天的月份的天数

           Calendarcalendar  =Calendar.getInstance();

           calendar.set(year,2,1);

           //c.setTime(d2);

           //本月1号,天数-1后获取前一个月最后一天

           calendar.add(calendar.DAY_OF_MONTH, -1);

           System.out.println("本年2月有"+calendar.get(calendar.DAY_OF_MONTH)+"天");

           System.out.println("calendar.getTime()和Date date时间表示一致:"+calendar.getTime());

       }

@Test

       public voidTest3() throwsParseException {

       /*1.3  求两个时间点的时间差

       有2个字符串形式的日期数据,计算它们相距多少天?

              "2014年09/28 23时13分01秒"

              "2009-02月12日12时02分01秒"*/

           Strings1 = "2014年09/28 23时13分01秒";

           Strings2 = "2009-02月12日 12时02分01秒";

           SimpleDateFormatsdf = new SimpleDateFormat("yyyy年MM/dd HH时mm分ss秒");

           SimpleDateFormatsdf1= new SimpleDateFormat("yyyy-MM月dd日 HH时mm分ss秒");

           Calendarc= Calendar.getInstance();

           c.setTime(sdf.parse(s1));

           long t1= c.getTimeInMillis();

           c.setTime(sdf1.parse(s2));

           long t2= c.getTimeInMillis();

           if(t1>t2) {

              System.out.println("相差:"+(t1-t2)/(24*60*60*1000)+"天");

           }else {

              System.out.println("相差:"+(t2-t1)/(24*60*60*1000)+"天");

           }

       }

上一篇 下一篇

猜你喜欢

热点阅读