java獲取各種格式的時間,獲取昨天明天日期,獲取一天的開始結束時間

一、獲取當前日期和時間

1、使用Date和DateFormat

      Date now = new Date();

      DateFormat df1 = DateFormat.getDateInstance(); //格式化後的時間格式:2016-2-19 
      String str1 = d1.format(now);
      DateFormat d2 = DateFormat.getDateTimeInstance();//格式化後的時間格式:2016-2-19 20:54:53
      String str2 = d2.format(now);
      DateFormat d3 = DateFormat.getTimeInstance();//格式化後的時間格式:20:54:53
      String str3 = d3.format(now);
      DateFormat d4 = DateFormat.getInstance(); //格式化後的時間格式:16-2-29 下午8:54
      String str4 = d4.format(now);

      DateFormat d5 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);//格式化後的時間格式:2016年2月19日 星期五 下午08時54分53秒 CST
      String str5 = d5.format(now);
      DateFormat d6 = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);//格式化後的時間格式:2016年2月19日 下午08時54分53秒
      String str6 = d6.format(now);
      DateFormat d7 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);//格式化後的時間格式:16-2-19 下午8:54
      String str7 = d7.format(now);
      DateFormat d8 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);//格式化後的時間格式:2016-2-19 20:54:53
      String str8 = d8.format(now);

2、使用canlinder


      Calendar c = Calendar.getInstance();
      int year = c.get(Calendar.YEAR);//獲取年份
      int month=c.get(Calendar.MONTH)+1;//獲取月份
      int day=c.get(Calendar.DATE);//獲取日
      int minute=c.get(Calendar.MINUTE);//分
      int hour=c.get(Calendar.HOUR);//小時
      int second=c.get(Calendar.SECOND);//秒
      int WeekOfYear = c.get(Calendar.DAY_OF_WEEK);//顯示當前日期是一週的第幾天,週一就是1,週五就是5

      String date=year +"年"+ month +"月"+ day + "日";//格式:2016年2月19日
      String time=hour +"時"+ minute +"分"+ second +"秒";//格式:8時54分53秒
      String date1=c.getTime()//格式:Fri Feb 19 20:54:53 CST 2016

3、使用Date和SimpleDateFormat(優點:24小時)

      Date date = new Date();
      SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String sDateSuffix = dateformat.format(date);
總結:自己最常用的時第三種方法

二、獲取昨天和明天的日期

      Date date=new Date();//取時間
      Calendar calendar = new GregorianCalendar();
      calendar.setTime(date);
      calendar.add(calendar.DATE,-1);//把日期往前減少一天,若想把日期向後推一天則將負數改爲正數
      date=calendar.getTime(); 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     String dateString = formatter.format(date);

三、獲取一天的開始時間和結束時間

     Date date=new Date();//取時間
     date.clearTime()
     Calendar calendar = new GregorianCalendar();
     calendar.setTime(date);
     calendar.set(Calendar.HOUR,0)
     calendar.set(Calendar.MINUTE,0)
     calendar.set(Calendar.SECOND,0)
     calendar.set(Calendar.MILLISECOND,0)
     System.out.println("開始時間:"+calendar.getTime())
     calendar.set(Calendar.HOUR,23)
     calendar.set(Calendar.MINUTE,59)
     calendar.set(Calendar.SECOND,59)
     calendar.set(Calendar.MILLISECOND,999)
     System.out.println("結束時間:"+calendar.getTime())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章