This is the 27th day of my participation in the August More Text Challenge


Related articles

Summary of Java utility classes: Java utility classes


  • This article will be updated with the daily work, as a record.
  • In my daily work, I would unify the time-related methods of many business scenarios into tool classes for use.
  • Convenient for later use.
  • Hope these tool classes are helpful!
  • Click follow oh ~

A collection of time utility classes

Get the time from a week ago

  • Business scenarios:

    • You need to collect statistics on the data list within one week after the current time is rolled back.
  • public static String sevenDatysAgo(a){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            // Last seven days
            c.setTime(new Date());
            c.add(Calendar.DATE, - 7);
            Date d = c.getTime();
            String day = format.format(d);
            day = day+"00:00:00";
            return day;
    }
    Copy the code
  • Demonstration effect

  •     public static void main(String[] args) {
           // This method returns the current time one week ago zero minutes zero seconds
            System.out.println(sevenDatysAgo());
        }
    Copy the code

②, get the month before several months

  • The business scenario

    • You can choose to use this tool class if it involves statistics across the New Year.
    • For example, the current data analysis starts three months back.
  • public static String[] getDateBeforeMonth(String dateKey, Integer length){
            String[] arrData = new String[2];
             try {
                //dateKey is the date passed in, and length is the month that needs to be pushed forward
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                Calendar c = Calendar.getInstance();
                Date nowMonth = format.parse(dateKey);
                c.setTime(nowMonth);
                c.add(Calendar.MONTH, -length);
                Date m3 = c.getTime();
                String mon3 = format.format(m3);
                System.out.println("The past"+length+"Month:"+mon3);
                arrData[0] = mon3;
                arrData[1] = dateKey;
                return arrData;
                } catch (ParseException e) {
                e.printStackTrace();
             }
             return arrData;
    }
    Copy the code
  • Demonstration effect

  • public static void main(String[] args) {
            getDateBeforeMonth("The 2021-08".6);
    }
    Copy the code

③ Hours turn to minutes

  • The business scenario

    • Statistics page for easy viewing.
  • public static int hoursTOminute(String date) {
            String[] dataArr = date.split("Hour");
            int Hminute = Integer.parseInt(dataArr[0]) * 60;
            int Mminute = Integer.parseInt(dataArr[1].replace("Points".""));
            int hoursToMinute = Hminute + Mminute;
            return hoursToMinute;
    }
    Copy the code
  • Demonstration effect

  • public static void main(String[] args) {
            String str = "3 hours and 24 minutes.";
            System.out.println(str+":"+hoursTOminute(str));
    }
    Copy the code

④ Get the date of N hours

  • The business scenario

    • It is generally used for data batch running
    • For example, fake data to make pages move and frame time frames!
  • Public static String getAfterHourCycleByHour(Date Date, Date Date, Date Date) String days) { int daysInt = Integer.parseInt(days); Calendar canlendar = Calendar.getInstance(); canlendar.setTime(date); canlendar.add(Calendar.HOUR, daysInt); SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdfd.format(canlendar.getTime()); return dateStr; }Copy the code
  • Demonstration effect

  • public class test {
        public static void main(String[] args) {
            Date date = new Date();
            String endTime = DateUtils.getAfterHourCycleByHour(date, "2"); System.out.println(endTime); }}Copy the code

Calculate a person’s age according to the date of birth

  • The business scenario

    • This is the age of a person based on the date of birth entered by someone else. The scenario is very simple.
  • /** * Age is calculated based on birth date **@returnFuture dates return 0 */
        public static int getAge(Date birthDay) throws Exception {
            Calendar cal = Calendar.getInstance();
    
            if (cal.before(birthDay)) {
                return 0;
            }
    
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);
    
            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
    
            int age = yearNow - yearBirth;
    
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {
                    if(dayOfMonthNow < dayOfMonthBirth) { age--; }}else{ age--; }}return age;
        }
    Copy the code
  • Demonstration effect

  • public class test {
        public static void main(String[] args) throws Exception{
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDay = df.parse("1996-08-27"); System.out.println(DateUtils.getAge(birthDay)); }}Copy the code

Get the start time of the week

  • The business scenario

    • Statistical analysis of this week’s data
  • public static Date getBeginDayOfWeek(a) {
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
            if (dayofweek == 1) {
                dayofweek += 7;
            }
            cal.add(Calendar.DATE, 2 - dayofweek);
            return getDayStartTime(cal.getTime());
    }
    Copy the code
  • Demonstration effect

  • public class test {
        public static void main(String[] args) throws Exception{ System.out.println(DateUtils.getBeginDayOfWeek()); }}Copy the code

To be continued


The road ahead is long, I see no end, I will search high and low

If you think I bloggers write well! Writing is not easy, please like, follow, comment and give encouragement to the blogger ~ Hahah