Detailed Java commonly used time operation "practical" _java

Source: Internet
Author: User

Projects often have to deal with the needs of time, the following is a number of commonly used operations collation, easy to reuse later and do related review.

1. Convert String to date

/**
   * String converted to date
   * @param datestr the date to be converted
   * @param dateformat date format yyyy-mm-dd/yyyy-mm-dd
   HH:mm:ss
  * * public static date ToDate (String datestr, SimpleDateFormat dateformat) throws parseexception{
    date = null;
    try {
      date = Dateformat.parse (DATESTR);
    } catch (ParseException e) {
      logger.debug ("Fail to convert String t O Date, {} ", datestr);
    }
    return date;
  }

2. Time Stamp Turn date

/**
   * Timestamp turn date
   * @param date
   * @return
   /public
  static String datetotime (Long, SimpleDateFormat DateFormat) throws parseexception{
     String data = null;
     try {
       Dateformat.format (new Date (time*1000));  
     } catch (Exception e) {
       logger.debug ("Fail to convert Long" Date, {} ", time);
     }
     return data;
  }

3. Date format to String

/**
   * Date formatted as String
   * @param date
   * @param dateformat *
   @return
   * @throws parseexception
   */< C22/>public static String toString (date date, SimpleDateFormat DateFormat) throws parseexception{return
    Dateformat.format (date);
  

4. Get the date before or after the specified date, very second for 00:00:00

 /**
   * Get the date before or after the specified date
   * @param date 
   * @param num positive number is followed by a negative number before
   * @return yyyy-mm-dd 00:00:00
  * * public static date getspecificdate (date date, int num) {
    Calendar todaycal = Calendar.getinstance ();
    Todaycal.settime (date);
    Calendar C = calendar.getinstance ();
    C.set (Todaycal.get (calendar.year), Todaycal.get (Calendar.month), Todaycal.get (calendar.day_of_month) + num, 0, 0, 0); return
    c.gettime ();
  }

5. Gets the date before or after the specified date, in minutes seconds for the current

  /**
   * Gets the date before or after the specified date
   * @param date 
   * @param num positive number is before, minus is after
   * @return Yyyy-mm-dd + current minute
   */< C20/>public Static Date Getspecificdateandhhmmss (date Date,int num) {
    Calendar c = calendar.getinstance (); 
    C.settime (date); 
    int Day=c.get (calendar.date); 
    C.set (calendar.date,day-num); 
    return C.gettime (); 
  }

6. Converts time strings of the type to the hour, minute

  /**
   * Converts the time string of the type to
   hh-mm-ss-->> hh-mm
   * @param times * @return/public
  static String Timetohhmm (String time) {return
    time.substring (0, Time.length ()-3);
  }

7. Get the time and minutes of a date

  /**
   * Get a date's time, minute
   * @param date
   * @return hh-mm
  /public static String Gethm (date date) {
    Calendar CA = calendar.getinstance (); 
    Ca.settime (date);
    Integer hour = ca.get (calendar.hour_of_day);/hour 
    integer minute = ca.get (Calendar.minute);//split
    String Rs_ hour = Hour.tostring ();
    String Rs_minute = minute.tostring ();
    if (rs_hour.length () = = 1) {
      Rs_hour = "0" + hour;
    }
    if (rs_minute.length () = = 1) {
      Rs_minute = "0" + minute;
    }
    return Rs_hour + ":" + Rs_minute;
  }

8.time type of time string-->> the number of seconds starting at 0 point

  /**
   * Time string-->> the number of seconds starting at 0
   * @param time hh-mm/hh-mm-ss
   * @return/public
  static Integ Er timetoseconds (String time) {
     string[] timesplit = null;
     int hours = 0,minutes = 0,seconds = 0;
     try {
       timesplit = Time.split (":");
       if (timesplit.length = = 2) {
         hours = integer.valueof (timesplit[0)) *60*60;
         minutes = integer.valueof (timesplit[1]) *60;
       } else if (timesplit.length = = 3) {
         hours = integer.valueof (timesplit[0)) *60*60;
         minutes = integer.valueof (timesplit[1]) *60;
         seconds = integer.valueof (timesplit[2]);
       } else{
         logger.debug ("Fail to convert", time);
       }
     catch (Exception e) {
       logger.debug (" Fail to convert ' time, {} ', time);
       throw e;
     }
    Return hours + minutes + seconds;
  }

9.0-point number of seconds to start time-->> Hh-mm-ss

  /**
   * 0 o'clock seconds to start-->> hh-mm-ss
   * @param durationseconds
   * @return/public
  static String getduration (int durationseconds) { 
    int hours = durationseconds/(60*60); 
    int leftseconds = durationseconds% (60*60); 
    int minutes = LEFTSECONDS/60; 
    int seconds = leftseconds%; 
    StringBuffer sbuffer = new StringBuffer (); 
    Sbuffer.append (Addzeroprefix (Hours)); 
    Sbuffer.append (":"); 
    Sbuffer.append (Addzeroprefix (minutes)); 
    Sbuffer.append (":"); 
    Sbuffer.append (Addzeroprefix (seconds)); 
    return sbuffer.tostring (); 
  } 
  public static String Addzeroprefix (int number) { 
    if (number < ten) return 
      "0" +number; 
    else return 
      "" +number; 
  }

10. Compare the number of seconds between two dates

  /**
   * Compare the number of seconds between two dates
   * @param startdate
   * @param enddate
   * @return/public
  static int Gettimeseconds (Date startdate,date enddate) {
     Long a = Enddate.gettime ();
     Long B = startdate.gettime ();
     return (int) (A-B)/1000);
  

11. Determine if there is an intersection of two time periods

  /**
   * Compare the number of seconds between two dates
   * @param startdate
   * @param enddate
   * @return/public
  static int Gettimeseconds (Date startdate,date enddate) {
     Long a = Enddate.gettime ();
     Long B = startdate.gettime ();
     return (int) (A-B)/1000);
  

12. Obtain a specified date of the week (1-7 representing Monday to Sunday respectively)

  /**
   * Get a specified date is the day of the week (1-7 for Monday to Sunday respectively)
   * @return
  /public static int DayOfWeek (date date) {
    Calendar now = Calendar.getinstance ();
    Now.settime (date);
    Boolean isfirstday = (Now.getfirstdayofweek () = = Calendar.sunday);
    int weekday = Now.get (Calendar.day_of_week);
    if (isfirstday) {
      weekday = weekday-1;
      if (weekday = = 0) {
        weekday = 7;
      }
    }
    return weekday;
  }

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.