JAVA擷取時間的N種方法

來源:互聯網
上載者:User
import java.sql.Timestamp;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Locale;public class DateUtils {/**       * 獲得目前時間,格式yyyy-MM-dd hh:mm:ss       * @param format       * @return       */      public static String getCurrentDate(){           return getCurrentDate("yyyy-MM-dd HH:mm:ss");       }       /**       * 獲得目前時間,格式自訂       * @param format       * @return       */      public static String getCurrentDate(String format){           Calendar day=Calendar.getInstance();            day.add(Calendar.DATE,0);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"           String date = sdf.format(day.getTime());           return date;       }       /**       * 獲得昨天時間,格式自訂       * @param format       * @return       */      public static String getYesterdayDate(String format){           Calendar day=Calendar.getInstance();            day.add(Calendar.DATE,-1);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"           String date = sdf.format(day.getTime());           return date;       }        /**          * @param date1 需要比較的時間 不可為空(null),需要正確的日期格式 ,如:2009-09-12         * @param date2 被比較的時間  為空白(null)則為目前時間          * @param stype 傳回值類型   0為多少天,1為多少個月,2為多少年          * @return          * 舉例:        * compareDate("2009-09-12", null, 0);//比較天        * compareDate("2009-09-12", null, 1);//比較月        * compareDate("2009-09-12", null, 2);//比較年        */         public static int compareDate(String startDay,String endDay,int stype){              int n = 0;              //String[] u = {"天","月","年"};              String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd";                            endDay = endDay==null?getCurrentDate("yyyy-MM-dd"):endDay;                            DateFormat df = new SimpleDateFormat(formatStyle);              Calendar c1 = Calendar.getInstance();              Calendar c2 = Calendar.getInstance();              try {                  c1.setTime(df.parse(startDay));                  c2.setTime(df.parse(endDay));            } catch (Exception e3) {                  System.out.println("wrong occured");              }              //List list = new ArrayList();              while (!c1.after(c2)) {                   // 迴圈對比,直到相等,n 就是所要的結果                  //list.add(df.format(c1.getTime()));    // 這裡可以把間隔的日期存到數組中 列印出來                  n++;                  if(stype==1){                      c1.add(Calendar.MONTH, 1);          // 比較月份,月份+1                  }                  else{                      c1.add(Calendar.DATE, 1);           // 比較天數,日期+1                  }              }              n = n-1;              if(stype==2){                  n = (int)n/365;              }        //         System.out.println(startDay+" -- "+endDay+" 相差多少"+u[stype]+":"+n);                    return n;          }        /**        * 判斷時間是否符合時間格式        */      public static boolean isDate(String date, String dateFormat) {           if (date != null) {               java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(dateFormat);               format.setLenient(false);               try {                   format.format(format.parse(date));               } catch (ParseException e) {                   // TODO Auto-generated catch block                   return false;               }               return true;           }           return false;       }        /**        * 實現給定某日期,判斷是星期幾        * date:必須yyyy-MM-dd格式        */       public static String getWeekday(String date){           SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");          SimpleDateFormat sdw = new SimpleDateFormat("E");          Date d = null;          try {              d = sd.parse(date);          } catch (ParseException e) {              e.printStackTrace();          }        return sdw.format(d);        }        /**        * 用來全域控制 上一周,本周,下一周的周數變化        */      private static int weeks = 0;       /**       * 獲得當前日期與本周一相差的天數       */       private static int getMondayPlus() {            Calendar cd = Calendar.getInstance();            // 獲得今天是一周的第幾天,星期日是第一天,星期二是第二天......            int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);            if (dayOfWeek == 1) {                return -6;            } else {                return 2 - dayOfWeek;            }        }        /**        * 獲得本周星期一的日期        */       public static String getCurrentMonday(String format) {            weeks = 0;            int mondayPlus = getMondayPlus();            Calendar currentDate=Calendar.getInstance();            currentDate.add(Calendar.DATE, mondayPlus);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"            String date = sdf.format(currentDate.getTime());            return date;        }        /**        * 獲得上周星期一的日期        */       public static String getPreviousMonday(String format) {            weeks--;            int mondayPlus = getMondayPlus();            Calendar currentDate=Calendar.getInstance();            currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"            String date = sdf.format(currentDate.getTime());            return date;        }        /**        * 獲得下周星期一的日期        */       public static String getNextMonday(String format) {            weeks++;            int mondayPlus = getMondayPlus();       //     GregorianCalendar currentDate = new GregorianCalendar();            Calendar currentDate=Calendar.getInstance();            currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"            String date = sdf.format(currentDate.getTime());            return date;        }        /**        * 獲得相應周的周日的日期        * 此方法必須寫在getCurrentMonday,getPreviousMonday或getNextMonday方法之後        */       public static String getSunday(String format) {            int mondayPlus = getMondayPlus();            Calendar currentDate=Calendar.getInstance();            currentDate.add(Calendar.DATE, mondayPlus + 7 * weeks + 6);            SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"            String date = sdf.format(currentDate.getTime());            return date;        }            /**        *method 將字串類型的日期轉換為一個timestamp(時間戳記java.sql.Timestamp)        *@param dateString 需要轉換為timestamp的字串        *@return dataTime timestamp        */      public static Timestamp string2Time(String dateString) {           DateFormat dateFormat;           dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);// 設定格式           dateFormat.setLenient(false);           java.util.Date date = null;           try {               date = dateFormat.parse(dateString);           } catch (ParseException e) {               // TODO Auto-generated catch block               e.printStackTrace();           }   //      java.sql.Timestamp dateTime = new java.sql.Timestamp(date.getTime());           return new Timestamp(date.getTime());// Timestamp類型,timeDate.getTime()返回一個long型       }         /**       *method 將字串類型的日期轉換為一個Date(java.sql.Date)       *        * @param dateString       *            需要轉換為Date的字串       *@return dataTime Date       */      public final static java.sql.Date string2Date(String dateString) {           DateFormat dateFormat;           dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);           dateFormat.setLenient(false);           java.util.Date date = null;           try {               date = dateFormat.parse(dateString);           } catch (ParseException e) {               // TODO Auto-generated catch block               e.printStackTrace();           }   //      java.sql.Date dateTime = new java.sql.Date(date.getTime());// sql類型           return new java.sql.Date(date.getTime());       }   }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.