SoFunction
Updated on 2025-03-11

Analysis of Android DateUtil time tool class usage example

introduction

Time is a common processing requirement in software development, including obtaining the current time, time formatting, time comparison, time difference calculation and other operations. To simplify the development process, you can write a time tool class to encapsulate these commonly used time operation methods.

Because the tool class time class is mainly divided into formatting and time calculation, it is done to split it

Main functions formatting time tool category

Time tool processing class

DateUtil Time Tool Class

Functional introduction

The time tool class encapsulates the following commonly used functions:

  • Get the current time: Get the current date and time of the system.
  • Format time: Format the date object or timestamp to the specified time format.
  • Parsing time: parses the string time into a date object.
  • Get time difference: Calculate the time difference between two dates, including days, hours, minutes, etc.
  • Determine time interval: determines whether the specified time is within a given time interval.
  • Judge Leap Year: Judge whether the specified year is a leap year.
  • Get year, month, week, etc.: Extract year, month, week and other information from date objects.

Main methods and functions

  • getCurrentDate(String pattern): Get the string representation of the current time.
  • formatToStr(long timestamp, String pattern): Format the timestamp to a string of the specified format.
  • formatToStr(Date date, String pattern): Format the date object into a string in the specified format.
  • formatStringDate(String dateString, String format): Format the string time according to the specified format.
  • getCurrentTime(): Get the date object of the current time.
  • formatTime(Date date, String pattern): Format the date object to a time string in the specified format.
  • parseTime(String time, String pattern): parses the time string in the specified format as a date object.
  • getTimeDifference(Date date1, Date date2, TimeUnit timeUnit): Calculate the time difference between two dates.
  • isInTimeRange(Date time, Date startTime, Date endTime): Determine whether the specified time is within a given time interval.
  • isLeapYear(int year): Determine whether the specified year is a leap year.
  • getYearFromDate(Date date): Gets the year of the object on the specified date.
  • getMonthFromDate(Date date): Gets the month of the object on the specified date.
  • getWeekdayFromDate(Date date): Gets the day of the week of the object on the specified date.

Common usage examples

// Get the current timeDate currentTime = ();

// Format timeString formattedTime = (currentTime, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);

// Analysis timeString timeString = "2023-07-14 12:00:00";
Date parsedTime = (timeString, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);

// Get the time differenceDate startTime = new Date();
Date endTime = new Date(() + (2));
long timeDifference = (startTime, endTime, );

//Judge time intervalDate time = new Date();
Date startTime = new Date(() - (1));
Date endTime = new Date(() + (1));
boolean isInTimeRange = (time, startTime, endTime);

// Judge leap yearint year = 2023;
boolean isLeapYear = (year);

// Get year, month, weekint yearFromDate = (currentTime);
int monthFromDate = (currentTime);
int weekdayFromDate = (currentTime);

Sample code

Here is a sample code for a simple time tool class:

import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
  * @author: xtxiaolu
  * @date: 2023/7/14
  * Description: Main functions formatting time tool class
  */
public class DateUtil {
    // Date format year, for example: 2022, 2023    public static final String FORMAT_YYYY = "yyyy";
    // Other format constants...    private static final TimeZone DEFAULT_TIMEZONE = ();
    private static TimeZone DefaultTimeZone = ();
    /**
      * Get the string representation of the current time
      *
      * @param pattern Time format
      * @return String representation of the current time
      */
    public static String getCurrentDate(String pattern) {
        return formatToStr(new Date(), pattern);
    }
    /**
      * Format the timestamp to a string of the specified format
      *
      * @param timestamp timestamp
      * @param pattern Time format
      * @return Formatted Time String
      */
    public static String formatToStr(long timestamp, String pattern) {
        return formatToStr(new Date(timestamp), pattern);
    }
    /**
      * Format the date object to a string in the specified format
      *
      * @param date date object
      * @param pattern Time format
      * @return Formatted Time String
      */
    public static String formatToStr(Date date, String pattern) {
        DateFormat dateFormat = getDateFormat(pattern);
        return (date);
    }
    /**
      * Get the date format object in the specified format
      *
      * @param pattern Time format
      * @return Date formatting object
      */
    private static DateFormat getDateFormat(String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        (DEFAULT_TIMEZONE);
        return dateFormat;
    }
    /**
      * Format string time to the specified format
      *
      * @param dateString String time
      * @param format
      * @return Formatted Time String
      */
    public static String formatStringDate(String dateString, String format) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat(format);
        try {
            Date date = (dateString);
            return (date);
        } catch (ParseException |  e) {
            ();
        }
        return "";
    }
    /**
      * Get the date object of the current time
      *
      * @return Date object of the current time
      */
    public static Date getCurrentTime() {
        return new Date();
    }
    /**
      * Format the date object to a time string in the specified format
      *
      * @param date date object
      * @param pattern Time format
      * @return Formatted Time String
      */
    public static String formatTime(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return (date);
    }
    /**
      * parse the time string in the specified format as a date object
      *
      * @param time Time string
      * @param pattern Time format
      * @return parsed date object
      * @throws ParseException parsing exception
      */
    public static Date parseTime(String time, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return (time);
        } catch ( e) {
            throw new RuntimeException(e);
        }
    }
    /**
      * Calculate the time difference between two dates and return the difference of the specified time unit
      *
      * @param date1 First date object
      * @param date2 The second date object
      * @param timeUnit TimeUnit
      * @return The difference in time difference
      */
    public static long getTimeDifference(Date date1, Date date2, TimeUnit timeUnit) {
        long difference = () - ();
        return (difference, );
    }
    /**
      * Determine whether the specified time is within a given time interval
      *
      * @param time Time to be judged
      * @param startTime The start time of the time interval
      * @param endTime The end time of the time interval
      * @return Return true if the specified time is within the time interval; otherwise, return false
      */
    public static boolean isInTimeRange(Date time, Date startTime, Date endTime) {
        return (startTime) && (endTime);
    }
    /**
      * Determine whether the specified year is a leap year
      *
      * @param year
      * @return Return true if it is a leap year; otherwise, return false
      */
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }
    /**
      * Get the year of the object on the specified date
      *
      * @param date date object
      * @return Year
      */
    public static int getYearFromDate(Date date) {
        Calendar calendar = ();
        (date);
        return ();
    }
    /**
      * Get the month of the object on the specified date
      *
      * @param date date object
      * @return Month
      */
    public static int getMonthFromDate(Date date) {
        Calendar calendar = ();
        (date);
        return () + 1;
    }
    /**
      * Get the day of the week of the specified date object
      *
      * @param date date object
      * @return Week, 1 means Monday, 2 means Tuesday, etc.
      */
    public static int getWeekdayFromDate(Date date) {
        Calendar calendar = ();
        (date);
        return (Calendar.DAY_OF_WEEK);
    }
}

TimeUtil Time Tool Class

The time tool class provides a series of methods for processing time, including obtaining the current time, formatting time, judging time intervals, and calculating time difference. This tool class is based on the latest Android API and provides a more concise and easy-to-use approach.

Method List

  • getCurrentWeekOfMonth(): Get the current time as of the month.
  • getCurrentDayOfWeek(): Get the current time as the day of the week.
  • getCurrentDayOfWeekText(): Returns the text representation of the current date of the week.
  • isTimeInRange(time, startTime, endTime): Determines whether the specified time is within a given time interval.
  • isTimeInRange(time, startTime, endTime): Determines whether the specified time is within a given time interval.
  • isInTimeRange(currentTime, startTime, endTime): Determines whether the specified time is within a given time interval.
  • calculateDaysDifference(startDate, endDate): Calculate the number of days that differ between two dates.
  • calculateTimeDifference(date): Returns a friendly time span representation.

Method Example

// Get the current week of this monthint weekOfMonth = ();
// Get what day of the current time is this weekint dayOfWeek = ();
// Returns the text representation of the current date of the weekString dayOfWeekText = ();
// Determine whether the specified time is within the time intervalboolean isInRange = (time, startTime, endTime);
// Calculate the number of days that differ between two dateslong daysDifference = (startDate, endDate);
// Return to the friendly time span representationString timeDifference = (date);

Sample code

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
  * @author: xtxiaolu
  * @date: 2023/7/14
  * Description: Time tool processing class
  */
public class TimeUtil {
    /**
      * Get the current week of the month
      *
      * @return What week of the month
      */
    public static int getCurrentWeekOfMonth() {
        Calendar calendar = ();
        int weekOfMonth = (Calendar.WEEK_OF_MONTH);
        return weekOfMonth;
    }
    /**
      * Get the current time as the day of the week
      *
      * @return What day of the week (1 represents Monday, 7 represents Sunday)
      */
    public static int getCurrentDayOfWeek() {
        LocalDate currentDate = ();
        DayOfWeek dayOfWeek = ();
        int dayOfWeekValue = ();
        return dayOfWeekValue;
    }
    /**
      * Return to the current date is the day of the week
      *
      * @return For example: Sunday, Monday, Saturday, etc.
      */
    public static String getCurrentDayOfWeekText() {
        Calendar calendar = ();
        int dayOfWeek = (Calendar.DAY_OF_WEEK);
        // Get the text of the day of the week        DateFormatSymbols symbols = new DateFormatSymbols(());
        String[] dayOfWeekTexts = ();
        if (dayOfWeek >=  && dayOfWeek <= ) {
            return dayOfWeekTexts[dayOfWeek];
        } else {
            return "";
        }
    }
    /**
      * Determine whether the specified time is within the time interval
      *
      * @param time Time to be judged
      * @param startTime The start time of the time interval
      * @param endTime The end time of the time interval
      * @return Return true if the specified time is within the time interval; otherwise, return false
      */
    public static boolean isTimeInRange(Calendar time, Calendar startTime, Calendar endTime) {
        return (startTime) >= 0 && (endTime) <= 0;
    }
    /**
      * Determine whether the specified time is within the time interval
      *
      * @param time Time to be judged
      * @param startTime The start time of the time interval
      * @param endTime The end time of the time interval
      * @return Return true if the specified time is within the time interval; otherwise, return false
      */
    public static boolean isTimeInRange(LocalDateTime time, LocalDateTime startTime, LocalDateTime endTime) {
        return (startTime) >= 0 && (endTime) <= 0;
    }
    /**
      * Determine whether the specified time is within the time interval
      *
      * @param currentTime Time to be judged
      * @param startTime The start time of the time interval
      * @param endTime The end time of the time interval
      * @return Return true if the specified time is within the time interval; otherwise, return false
      */
    public static boolean isInTimeRange(Date currentTime, Date startTime, Date endTime) {
        long currentTimeMillis = ();
        return currentTimeMillis >= () && currentTimeMillis <= ();
    }
    /**
      * Find the number of days between two dates
      * @param startDate Start time
      * @param endDate End time
      * @return Number of days
      */
    public static long calculateDaysDifference(Date startDate, Date endDate) {
        long differenceMillis = () - ();
        long differenceDays = (differenceMillis);
        return differenceDays;
    }
    /**
      * Return to friendly time span
      *
      * @param date The time required for formatting
      *
      * @return the fit time span
      * return less than 1 minute, return "just"
      * return less than 1 hour but greater than 0 minutes, return "X minutes ago"
      * return less than 1 day but greater than 0 hours, return "X hours ago"
      * return Yesterday, return "Yesterday"
      * return greater than 1 day, return "X days ago"
      */
    public static String calculateTimeDifference(Date date) {
        long currentTime = ();
        long timeDifference = currentTime - ();
        // Calculate the unit corresponding to the time difference        long seconds = timeDifference / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;
        if (days > 1) {
            // More than 1 day, return to "X days ago"            return days + "Day Ago";
        } else if (days == 1) {
            // Yesterday, return to "Yesterday"            return "yesterday";
        } else if (hours > 0) {
            // Less than 1 day but greater than 0 hours, return to "X hours ago"            return hours + "Hour ago";
        } else if (minutes > 0) {
            // Less than 1 hour but greater than 0 minutes, return to "X minutes ago"            return minutes + "Minutes ago";
        } else {
            // Less than 1 minute, return to "just"            return "just";
        }
    }
}

If the above time tool category is helpful to you, please like and collect it. This tool class is designed to simplify time processing and provides a series of easy-to-use methods to help you process time-related business logic more efficiently.

Whether it is to obtain a specific value of the current time, calculate the time difference, judge the time interval, or format the time, this tool class can meet your needs.

With this tool class, you can handle time operations more easily and improve development efficiency. If you find this tool class useful, please give you support so that it can be collected and used in the future.

For more information about Android DateUtil time tool category, please follow my other related articles!