Android 常用开发工具类之 DateUtilsBase (时间处理类)

本文介绍了一个实用的日期时间处理工具类,提供了多种日期时间格式化、比较、计算间隔等功能,帮助开发者高效处理各种日期时间相关的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本上所有项目都会使用到时间,而一个详细的时间处理类会帮你节省下许多时间处理上的麻烦。

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Description:时间日期处理
 * <p>
 * Author: mrj
 */
public class DateUtilsBase {
    /**
     * @param date
     * @param datePattern yyyy-MM-dd HH:mm
     */
    public static String formatDate(Date date, String datePattern) {
        DateFormat dateFormat = new SimpleDateFormat(datePattern);
        String ret = dateFormat.format(date);
        return ret;
    }

    /**
     * 格式化时间
     *
     * @param oldFormat
     *            原格式 yyyy-MM-dd HH:mm:ss
     * @param newFormat
     *            转换后的格式
     * @param dateStr
     *            需要转换的字符串
     * @return
     */
    public static String formatDate(String oldFormat, String newFormat,
                                    String dateStr) {
        SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
        SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);

        try {
            return sdf2.format(sdf1.parse(dateStr));
        } catch (Exception e) {
            // e.printStackTrace();
            return dateStr;
        }

    }

    /**
     * 格式化时间
     *
     * @param oldFormat
     *            原格式 yyyy-MM-dd HH:mm:ss
     * @param dateStr
     *            需要转换的字符串
     * @return
     */
    public static String formatTime(String oldFormat, String dateStr) {
        SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
        try {
            return sdf2.format(sdf1.parse(dateStr));
        } catch (Exception e) {
            // e.printStackTrace();
            return dateStr;
        }

    }

    /**
     * 获取当前Date
     *
     * @return Date类型时间
     */
    public static Date getNowTimeDate() {
        return new Date();
    }

    /**
     * 获取当前时间字符串
     * 格式为yyyy-MM-dd HH:mm:ss
     *
     * @return 时间字符串
     */
    public static String getNowTimeString() {
        return millis2String(System.currentTimeMillis(), "yyyy年MM月dd日 HH:mm:ss");
    }

    /**
     * @return 日期字符串
     */
    public static String getNowDateString() {
        return millis2String(System.currentTimeMillis(), "yyyy年MM月dd日");
    }

    /**
     * 判断是否同一天
     * <p>time格式为pattern
     *
     * @param time 时间字符串
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isSameDay(String time) {
        return isSameDay(string2Millis(time, "yyyy年MM月dd日"));
    }

    public static boolean isSameDay(Date date) {
        return isSameDay(date.getTime());
    }


    /**
     * 获取当前时间--如:2012-11-06 12:12:10
     */
    public static String getCurrentDate(String formatStr) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    /**
     * 返回时间对象
     * format为时间格式如("yyyy/MM/dd")
     * 返回null表示出错了
     */
    public static Date getDate(String time, String format) {
        Date date = null;
        try {
            SimpleDateFormat df = new SimpleDateFormat(format);
            df.setLenient(false);
            date = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return date;
    }

    /**
     * 毫秒换成几天前几小时几分钟
     */
    public static String periodToString(Long millisecond) {
        String str = "";
        long day = millisecond / 86400000;
        long hour = (millisecond % 86400000) / 3600000;
        long minute = (millisecond % 86400000 % 3600000) / 60000;
        if (day > 0) {
            str = String.valueOf(day) + "天";
        }
        if (hour > 0) {
            str += String.valueOf(hour) + "小时";
        }
        if (minute > 0) {
            str += String.valueOf(minute) + "分钟";
        }
        return str;
    }

    /**
     * 计算几天前;
     * 传入开始时间(比如"2012/11/06对应format为"yyyy/MM/dd";
     * 如果返回-1表示格式错误
     */
    public static int getIntervalDays(String beginTime, String format) {
        int dayNum = 0;
        try {
            Date start = getDate(beginTime, format);
            Date now = new Date();
            long res = now.getTime() - start.getTime();
            dayNum = (int) (((res / 1000) / 3600) / 24);
            System.out.println(dayNum + "天前");
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return dayNum;
    }

    /**
     * 计算几天前;
     * 传入开始时间(格式:2012-11-06 12:12:10)<br/>
     * 如果返回-1表示格式错误
     */
    public static int getIntervalDays(String beginTime) {
        return getIntervalDays(beginTime, "yyyy-MM-dd hh:mm:ss");
    }

    /**
     * 返回当前日期xxxx年x月xx日 星期x
     *
     * @return
     */
    public static String getDate() {
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        int w = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        String mDate = c.get(Calendar.YEAR) + "年" + c.get(Calendar.MONTH) + "月"
            + c.get(Calendar.DATE) + "日  " + weekDays[w];
        return mDate;
    }

    /**
     * 返回当前x月xx日 星期x
     *
     * @return
     */
    public static String getDateNew() {
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        int w = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        String mDate = c.get(Calendar.MONTH) + 1 + "月"
            + c.get(Calendar.DATE) + "日  ";
        return mDate;
    }

    /**
     * 返回毫秒
     *
     * @param date 日期
     * @return 返回毫秒
     */
    public static long getMillis(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.getTimeInMillis();
    }

    /**
     * 日期相加
     *
     * @param date 日期
     * @param day  天数
     * @return 返回相加后的日期
     */
    public static Date addDate(Date date, int day) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
        return c.getTime();
    }

    /**
     * 日期相减
     * 返回天
     *
     * @param date  日期
     * @param date1 日期
     * @return 返回相减后的日期
     */
    public static int diffDate(Date date, Date date1) {
        return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
    }

    /**
     * 日期相减
     * 返回分钟数
     *
     * @param date  日期
     * @param date1 日期
     * @return 返回相减后的日期
     */
    public static int diffDateMin(Date date, Date date1) {
        return (int) ((getMillis(date) - getMillis(date1)) / (1000 * 60));
    }

	 /**
     * 日期相减
     * 返回分钟数
     *
     * @param date  日期
     * @param now 当前时间
     * @return 返回相减后的日期
     */
    public static int diffDateMin(Date date, long now) {
        return (int) ((getMillis(date) - now) / (1000 * 60));
    }

	
	 /**
     * 将毫秒值转换为时间字符串
     *
     * @param millis  时间毫秒值
     * @param pattern 转换格式
     * @return 转换后的时间
     */
    private static String millis2String(long millis, String pattern) {
        return new SimpleDateFormat(pattern, Locale.getDefault()).format(new Date(millis));
    }

	
	
	 /**
     * 将时间字符串转换为毫秒值
     *
     * @param time  字符串时间
     * @param pattern 转换格式
     * @return 转换后的时间
     */
    private static long string2Millis(String time, String pattern) {
        try {
            return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

	
	 /**
     * 通过毫秒值判断是否为同一天
     *
     * @param millis  时间毫秒值
     * @return 是否同一天
     */
    private static boolean isSameDay(long millis) {
        long wee = (System.currentTimeMillis() / 86400000) * 86400000 - 8 * 3600000;
        return millis >= wee && millis < wee + 86400000;
    }
}

package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具 * * * Description: 将大部分的数据库操作放入这个中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID)的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值