ip地址,子网掩码,日期转换相关工具方法

阅读更多
/**
 *
 */
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;
import java.math.BigDecimal;


public class FormatUtil {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static NumberFormat numFormat = NumberFormat.getNumberInstance();

    private static NumberFormat percentFormat = NumberFormat.getPercentInstance();

    private FormatUtil() {

    }

    /**
     * 获取IP地址对应的主机域名,如果enalbelDNS为false,仅仅返回IP地址
     * @param s IP地址
     * @return 主机域名或IP地址
     * @throws UnknownHostException
     */
    public static String getDNSName(String s) throws UnknownHostException {
        InetAddress addr = InetAddress.getByName(s);
        String dns = addr.getHostName().trim();
        return dns.toLowerCase();
    }

    /**
     * 判断ipaddress是否属于私有地址
     * @param ipaddress
     * @return
     */
    public static boolean isPrivateIP(String ipaddress) throws ParseException {
        boolean flag = false;
        flag = isAddressInRange(ipaddress, "10.0.0.0", "10.255.255.255");

        if (!flag) {
            flag = isAddressInRange(ipaddress, "172.16.0.0", "172.31.255.255");
        }
        if (!flag) {
            flag = isAddressInRange(ipaddress, "192.168.0.0", "192.168.255.255");
        }
        if (!flag) {
            flag = isAddressInRange(ipaddress, "127.0.0.0", "127.255.255.255");
        }
        return flag;
    }

    /**
     * 校验是否为合法的IP地址
     * @param ipAddr
     * @return
     */
    public static boolean isValidIPAddr(String ipAddr) {
        try {
            getAddrArray(ipAddr);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public static boolean isValidNetmask(String ipAddr) {
        if (ipAddr == null) {
            return false;
        }

        StringTokenizer stringtokenizer = new StringTokenizer(ipAddr, ".");
        if (stringtokenizer.countTokens() != 4) {
            return false;
        }
        int ai[] = new int[4];
        try {
            for (int i = 0; i < 4; i++) {
                ai[i] = Integer.parseInt(stringtokenizer.nextToken());

            }
        } catch (NumberFormatException numberformatexception) {
            return false;
        }

        boolean evenFlag;
        if (ai[3] % 2 == 0) {
            evenFlag = true;
        } else {
            evenFlag = false;
        }
        if (!evenFlag) {
            // 应全是奇数
            for (int j = 3; j >= 0; j--) {
                // 将四个整数从上到下依次解析为二进制数,
                if (ai[j] == 0) {
                    return false;
                }

                while (ai[j] > 0) {
                    if (ai[j] % 2 == 0) {
                        return false;
                    }
                    ai[j] = ai[j] >> 1;

                }
            }
        } else {
            // 遇到奇数后就全是奇数
            for (int j = 3; j >= 0; j--) {
                if (ai[j] % 2 == 0) {
                    if (!evenFlag) {
                        return false;
                    }
                } else {
                    evenFlag = false;
                }

                while (ai[j] > 0) {
                    if (ai[j] % 2 == 0) {
                        if (!evenFlag) {
                            return false;
                        }
                    } else {
                        evenFlag = false;
                    }
                    ai[j] = ai[j] >> 1;
                }
            }
        }

        return true;

    }

    public static boolean isBroadcastAddr(String s) throws ParseException {
        long l = getAddrLong(s);
        long l1 = getAddrLong("0.0.0.255");
        long l2 = l & l1;
        return l2 == 255L;
    }

    /**
     * 检查一个IP地址是否在一些IP地址段内
     * @param s IP地址
     * @param vector 最小IP地址组
     * @param vector1 最大IP地址组
     * @return 该IP地址是否在范围内
     */
    public static boolean isAddressInRange(String s, Vector vector, Vector vector1) throws ParseException {
        if (vector == null || vector1 == null) {
            return true;
        }
        if (vector.size() != vector1.size()) {
            // TODO 抛出异常,异常要国际化
            return false;
        }
        long l = getAddrLong(s);
        if (l == 0L) {
            return false;
        }
        for (int i = 0; i < vector.size(); i++) {
            long l1 = getAddrLong((String) vector.elementAt(i));
            long l2 = getAddrLong((String) vector1.elementAt(i));
            if (l <= l2 && l >= l1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 校验两个子网是否有交叉
     * @param srcIpAddr
     * @param srcNetmask
     * @param destIpAddr
     * @param destNetmask
     * @return
     */
    public static boolean isNetInterCross(String srcIpAddr, String srcNetmask, String destIpAddr, String destNetmask) {
        boolean flag = false;
        try {
            if (FormatUtil.inNet(srcIpAddr, destIpAddr, destNetmask)) {
                flag = true;
            } else {
                String srcEndIpAddr = FormatUtil.getNetEndIP(srcIpAddr, srcNetmask);
                if (FormatUtil.inNet(srcEndIpAddr, destIpAddr, destNetmask)) {
                    flag = true;
                } else {
                    if (FormatUtil.inNet(destIpAddr, srcIpAddr, srcNetmask)) {
                        flag = true;
                    } else {
                        String destEndIpAddr = FormatUtil.getNetEndIP(destIpAddr, destNetmask);
                        if (FormatUtil.inNet(destEndIpAddr, srcIpAddr, srcNetmask)) {
                            flag = true;
                        }
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 检查一个IP地址是否在一些IP地址段内
     * @param s IP地址
     * @param vector 最小IP地址组
     * @param vector1 最大IP地址组
     * @return 该IP地址是否在范围内
     */
    public static boolean isAddressInRange(String ip, String startIP, String endIP) throws ParseException {
        if (ip == null || (startIP == null && endIP == null)) {
            return true;
        }
        long l = getAddrLong(ip);
        if (l == 0L) {
            return false;
        }
        boolean flag = true;
        if (startIP != null) {
            long l1 = getAddrLong(startIP);
            if (l < l1) {
                flag = false;
            }
        }
        if (endIP != null) {
            long l2 = getAddrLong(endIP);
            if (l > l2) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 检查一个IP地址是否在一个子网范围内
     * @param s IP地址
     * @param s1 子网地址
     * @param s2 子网掩码
     * @return IP地址是否在一个子网内
     */
    public static boolean inNet(String s, String s1, String s2) throws ParseException {
        if (s2.equals("255.255.255.255")) {
            if (s.equals(s1)) {
                return true;
            }
            return false;
        }
        long l = getAddrLong("255.255.255.255");
        long l1 = getAddrLong(s2);
        long l2 = getAddrLong(s1);
        l2 &= l1;
        long l3 = l ^ l1;
        long l4 = getAddrLong(s);
        if (l4 == 0L) {
            return false;
        }
        return l4 < l2 + l3 && l4 >= l2;
    }

    /**
     * 获取给定子网掩码的子网所包括的IP地址个数
     * @param s 以字符串表示网络地址
     * @param s1 以字符串表示的子网掩码
     * @return 子网所包括的IP地址个数,用long值表示
     */
    public static long getNumIPs(String s, String s1) throws ParseException {
        long l = getAddrLong("255.255.255.255");
        long l1 = getAddrLong(s1);
        if (l1 == l) {
            return 0L;
        }
        long l2 = getAddrLong(s);
        long l3 = l ^ l1;
        if (l1 == 0L || l2 == 0L || l1 > l || l3 > l) {
            throw new ParseException("ErrorIPFormat" + s + " " + s1, -1);
        }
        return l3;
    }

    public static String getNetworkNetMask(String network, String netmask) throws ParseException {
        if (network == null || netmask == null) {
            throw new ParseException("ErrorIPFormat" + network + " " + netmask,-1);
        }
        long l = getAddrLong("255.255.255.255");
        long l1 = getAddrLong(netmask);
        long l3 = l ^ l1;
        int num = 0;
        while (l3 > 0) {
            num++;
            l3 = l3 >> 1;
        }
        return network + "/" + (32 - num);
    }

    public static String[] parseNetworkNetMask(String networkNetmask) throws ParseException {

        if (networkNetmask == null) {
            throw new ParseException("ErrorIPFormat" + networkNetmask, -1);
        }
        int index = networkNetmask.indexOf("/");
        if (index == -1) {
            return null;
        }
        String netip = networkNetmask.substring(0, index);
        int num = 0;
        try {
            num = Integer.parseInt(networkNetmask.substring(index + 1));
            if (num > 32) {
                return null;
            }
        } catch (Exception ee) {
            return null;
        }
        long l = 1;

        int count = num;
        while (count > 1) {
            count--;
            l = (l << 1) + 1;
        }
        count = 32 - num;
        while (count > 0) {
            count--;
            l = l << 1;
        }
        String[] network = new String[2];
        network[0] = netip;
        network[1] = getAddrString(l);
        return network;
    }

    public static String getNetMask(String startip, String endip) throws ParseException {
        if (startip == null || endip == null) {
            throw new ParseException("ErrorIPFormat" + startip + " " + endip, -1);
        }
        long l = getAddrLong(startip);
        long l1 = getAddrLong(endip);
        long l2 = ~(l1 ^ l);
        return getAddrString(l2);
    }

    /**
     * @param startip
     * @param netmask
     * @return
     */
    public static String getNetEndIP(String startip, String p_netmask) throws ParseException {
        String netmask = p_netmask;
        if (startip != null && netmask != null) {
            if (startip.equals(netmask)) {
                netmask = "255.255.255.0";
            }
            if (netmask.equals("0.0.0.0")) {
                netmask = "255.255.255.0";
            }
        }
        long l = getAddrLong(startip);
        long l1 = getAddrLong(netmask);
        long l2 = ~l1 | l;
        return getAddrString(l2);
    }

    /**
     * 从一个给定IP(可能是节点地址)和子网掩码,获取子网地址
     * @param s IP地址
     * @param s1 子网掩码
     * @return 子网地址
     */
    public static String getNetAddr(String s, String p_s1) throws ParseException {
        String s1 = p_s1;
        if (s != null && s1 != null) {
            if (s.equals(s1)) {
                s1 = "255.255.255.0";
            }
            if (s1.equals("0.0.0.0")) {
                s1 = "255.255.255.0";
            }
        }
        long l = getAddrLong(s1);
        long l1 = getAddrLong(s);
        long l2 = l1 & l;
        return getAddrString(l2);
    }

    /**
     * 获取一个IP数组内最小或最大IP地址
     * @param vector IP地址数组
     * @param flag 是否是最大IP地址
     * @return 最大或最小IP地址
     */
    public static String getMinMaxAddr(Vector vector, boolean flag) throws ParseException {
        String s = (String) vector.firstElement();
        long l = getAddrLong(s);
        for (int i = 1; i < vector.size(); i++) {
            String s1 = (String) vector.elementAt(i);
            long l1 = getAddrLong(s1);
            if (!flag) {
                if (l1 < l) {
                    s = s1;
                    l = l1;
                }
            } else if (l1 > l) {
                s = s1;
                l = l1;
            }
        }
        return s;
    }

    /**
     * 获取一个子网内的所有IP地址
     * @param ip 网络地址
     * @param mask 网络掩码
     * @return IP地址字符数组
     */
    public static String[] getIPList(String ip, String mask) throws ParseException {
        String as[] = null;
        long l = getAddrLong("255.255.255.255");
        long l1 = getAddrLong(mask);
        if (l1 == l) {
            as = new String[1];
            as[0] = ip;
            return as;
        }
        long l2 = getAddrLong(ip);
        long l3 = l ^ l1;
        if (l1 == 0L || l2 == 0L || l1 > l || l3 > l) {
            throw new ParseException("ErrorIPFormat" + ip + " " + mask, -1);
        }
        if (l3 > 0x10000L) {
            throw new ParseException("ErrorIPFormat" + ip + " " + mask, -1);
        }
        if (l3 == 2L) {
            as = new String[1];
            as[0] = getAddrString(l2 + 1L);
            return as;
        }
        if ((l2 + l3) - 1L > l) {
            throw new ParseException(I18nUtil.getInstance().getValue("ErrorIPFormat") + ip + " " + mask, -1);
        }
        as = new String[(int) l3 - 1];
        for (int i = 0; i < l3 - 1; i++) {
            as[i] = getAddrString(l2 + 1L + i);
        }
        return as;
    }

    /**
     * 获取主机域名对应的IP地址
     * @param s 主机域名
     * @return 主机域名对应的IP地址,如果找不到相应的IP地址,返回主机域名
     */
    public static String getIP(String s) throws UnknownHostException {
        InetAddress addr = InetAddress.getByName(s);
        String ip = addr.getHostAddress().trim();
        return ip;
    }

    /**
     * 基于给定的网络地址,得到特定网络的缺省子网掩码。 这个方法基于对A、B、C类网络的猜测,返回相应的子网掩码。
     * @param s - 字符串表示的网络地址.
     * @return 缺省的网络掩码
     * @throws ParseException
     */
    public static String getDefaultNetMask(String s) throws ParseException {
        int ai[] = getAddrArray(s);
        if (ai[0] < 128) {// A类地址
            return "255.0.0.0";
        }
        if (ai[0] < 192) { // B类地址
            return "255.255.0.0";
        }
        // C、D、E类地址
        return "255.255.255.0";
    }

    /**
     * 将IP地址转换为long型值,这个方法检查输入的有效性
     * @param s IP地址
     * @return IP地址对应的long型值
     * @throws ParseException
     */
    public static long getAddrLong(String s) throws ParseException {
        int ai[] = getAddrArray(s);
        long l = 0L;
        for (int i = 0; i < 4; i++) {
            l |= (long) ai[i] << 8 * (3 - i);
        }
        return l;
    }

    /**
     * 将点分十进制表示的IP地址转换为长度为4的数组
     * @param s IP地址
     * @return 长度为4的数组,存放点号分开的值
     * @throws ParseException
     */
    public static int[] getAddrArray(String p_s) throws ParseException {
        String s = p_s;
        if (s == null) {
            throw new ParseException(I18nUtil.getInstance().getValue("ErrorIPFormat") + s, -1);
        }
        s = s.trim();
        StringTokenizer stringtokenizer = new StringTokenizer(s, ".");
        if (stringtokenizer.countTokens() != 4) {
            throw new ParseException(I18nUtil.getInstance().getValue("ErrorIPFormat") + s, stringtokenizer
                    .countTokens());
        }
        int ai[] = new int[4];
        for (int i = 0; i < 4; i++) {
            try {
                ai[i] = Integer.parseInt(stringtokenizer.nextToken());
            } catch (NumberFormatException numberformatexception) {
                throw new ParseException("ErrorIPFormat" + s, i);
            }
        }
        for (int i = 0; i < 4; i++) {
            if (ai[i] < 0 || ai[i] > 255) {
                throw new ParseException("ErrorIPFormat" + s, i);
            }
        }
        return ai;
    }

    /**
     * 将一个long型值转换为一个IP地址串,这个方法并不检查输入的有效性。
     * @param l long值数据
     * @return IP地址
     */
    public static String getAddrString(long l) {
        int ai[] = new int[4];
        for (int i = 0; i < 4; i++) {
            ai[i] = (int) (l >> 8 * (3 - i) & 255L);
        }
        return new String(ai[0] + "." + ai[1] + "." + ai[2] + "." + ai[3]);
    }

    /**
     * 获得一个yyyy-mm-dd hh:mm:ss格式的字符串的每个域的值
     * @param dateTime yyyy-mm-dd hh:mm:ss格式的字符串
     * @return 数组从0到5的六个元素分别是年,月,日,时,分,秒
     */
    public static String[] parseDateTime(String dateTime) {
        String[] result = new String[6];
        StringTokenizer token = new StringTokenizer(dateTime, " ");
        String date = token.nextToken();
        String time = token.nextToken();

        StringTokenizer dateToken = new StringTokenizer(date, "-");
        result[0] = dateToken.nextToken();
        result[1] = dateToken.nextToken();
        result[2] = dateToken.nextToken();

        StringTokenizer timeToken = new StringTokenizer(time, ":");
        result[3] = timeToken.nextToken();
        result[4] = timeToken.nextToken();
        result[5] = timeToken.nextToken();

        return result;
    }

    /**
     * 获得一个hh:mm:ss格式的字符串的每个域的值
     * @param time hh:mm:ss格式的字符串
     * @return 数组从0到2的三个元素分别是时,分,秒
     */
    public static String[] parseTime(String time) {
        String[] result = new String[3];
        StringTokenizer timeToken = new StringTokenizer(time, ":");
        result[0] = timeToken.nextToken();
        result[1] = timeToken.nextToken();
        result[2] = timeToken.nextToken();
        return result;
    }

    public static String to_Oracle_Date(String dateStr) {
        return "to_date('" + dateStr + "','yyyy-mm-dd hh24:mi:ss')";
    }

    public static String to_Oracle_Char(String dateField) {
        return "to_char(" + dateField + ",'yyyy-mm-dd hh24:mi:ss')";
    }

    /**
     * 将日期类型格式化成 yyyy-mm-dd hh24:mi:ss 格式
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        return simpleDateFormat.format(date);
    }

    /**
     * 将日期类型格式转换为yyyyMMddHHmmss的格式
     * @param date
     * @return
     */
    public static String formatDateToNumber(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(date);
    }

    /**
     * 将Web端如:2007-2-8 12:12:12 转换long型(以便入库)
     * @param str
     * @return
     */
    public static long formatDateToLong(String str) {
        long flag = 0;
        if (str != null && !str.equals("")) {
            try {
                flag = parseDate(str).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 根据数据库中long型时间,转换为时间的String到Web端显示
     * @param time
     * @return
     */
    public static String formatDateToString(long time) {
        String flag = "";
        if (time > 0) {
            flag = formatDate(new Date(time));
        }
        return flag;
    }

    /**
     * 从 yyyy-mm-dd hh24:mi:ss 格式的字符串中生成日期
     * @param str
     * @return
     * @throws ParseException
     */
    public static Date parseDate(String str) throws ParseException {
        return simpleDateFormat.parse(str);
    }

    public static Number parseNumber(String str) throws ParseException {
        return numFormat.parse(str);
    }

    /**
     * 格式化Number
     * @param value
     * @param minDigit 小数点后最小位数
     * @param maxDigit 小数点后最大位数
     * @return
     */
    public static String formatValue(Number number, int minDigit, int maxDigit) {
        synchronized (numFormat) {
            if (numFormat.getMaximumFractionDigits() != maxDigit) {
                numFormat.setMaximumFractionDigits(maxDigit);
            }
            if (numFormat.getMinimumFractionDigits() != minDigit) {
                numFormat.setMinimumFractionDigits(minDigit);
            }
            return numFormat.format(number);
        }
    }

    public static Number parsePercent(String str) throws ParseException {
        return percentFormat.parse(str);
    }

    /**
     * 格式化百分数
     * @param number
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String formatPercent(Number number, int minDigit, int maxDigit) {
        synchronized (percentFormat) {
            if (percentFormat.getMaximumFractionDigits() != maxDigit) {
                percentFormat.setMaximumFractionDigits(maxDigit);
            }
            if (percentFormat.getMinimumFractionDigits() != minDigit) {
                percentFormat.setMinimumFractionDigits(minDigit);
            }
            return percentFormat.format(number);
        }
    }

    /**
     * 格式化百分数
     * @param number
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String formatPercent(double number, int minDigit, int maxDigit) {
        synchronized (percentFormat) {
            if (percentFormat.getMaximumFractionDigits() != maxDigit) {
                percentFormat.setMaximumFractionDigits(maxDigit);
            }
            if (percentFormat.getMinimumFractionDigits() != minDigit) {
                percentFormat.setMinimumFractionDigits(minDigit);
            }
            return percentFormat.format(number);
        }
    }

    /**
     * 格式化百分数
     * @param number
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String formatPercent(float number, int minDigit, int maxDigit) {
        synchronized (percentFormat) {
            if (percentFormat.getMaximumFractionDigits() != maxDigit) {
                percentFormat.setMaximumFractionDigits(maxDigit);
            }
            if (percentFormat.getMinimumFractionDigits() != minDigit) {
                percentFormat.setMinimumFractionDigits(minDigit);
            }
            return percentFormat.format(number);
        }
    }

    /**
     * 格式化float
     * @param value
     * @param minDigit 小数点后最小位数
     * @param maxDigit 小数点后最大位数
     * @return
     */
    public static String formatValue(float value, int minDigit, int maxDigit) {
        synchronized (numFormat) {
            if (numFormat.getMaximumFractionDigits() != maxDigit) {
                numFormat.setMaximumFractionDigits(maxDigit);
            }
            if (numFormat.getMinimumFractionDigits() != minDigit) {
                numFormat.setMinimumFractionDigits(minDigit);
            }
            return numFormat.format(value);
        }
    }

    /**
     * 格式化double
     * @param value
     * @param minDigit 小数点后最小位数
     * @param maxDigit 小数点后最大位数
     * @return
     */
    public static String formatValue(double value, int minDigit, int maxDigit) {
        synchronized (numFormat) {
            if (numFormat.getMaximumFractionDigits() != maxDigit) {
                numFormat.setMaximumFractionDigits(maxDigit);
            }
            if (numFormat.getMinimumFractionDigits() != minDigit) {
                numFormat.setMinimumFractionDigits(minDigit);
            }
            return numFormat.format(value);
        }
    }

    /**
     * 获取流量速度的字符串
     * @param value
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String getbpsString(double p_value, int minDigit, int maxDigit) {
        double value = p_value;
        if (value > 1000) {
            value /= 1000;
            if (value > 1000) {
                value /= 1000;
                if (value > 1000) {
                    value /= 1000;
                    return formatValue(value, minDigit, maxDigit) + "Gbps";
                }
                return formatValue(value, minDigit, maxDigit) + "Mbps";
            }
            return formatValue(value, minDigit, maxDigit) + "Kbps";
        }
        return formatValue(value, 0, 0) + "bps";
    }

    public static String getBytesPerSecString(double p_value, int minDigit, int maxDigit) {
        double value = p_value;
        if (value > 1024) {
            value /= 1024;
            if (value > 1024) {
                value /= 1024;
                if (value > 1024) {
                    value /= 1024;
                    return formatValue(value, minDigit, maxDigit) + "GB/S";
                }
                return formatValue(value, minDigit, maxDigit) + "MB/S";
            }
            return formatValue(value, minDigit, maxDigit) + "KB/S";
        }
        return formatValue(value, 0, 0) + "B/S";
    }

    /**
     * 获取速度的字符串
     * @param value
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String getPsString(double p_value, int minDigit, int maxDigit, String unit) {
        double value = p_value;
        if (value >= 1024) {
            value /= 1024;
            if (value >= 1024) {
                value /= 1024;
                if (value >= 1024) {
                    value /= 1024;
                    return formatValue(value, minDigit, maxDigit) + "G" + unit;
                }
                return formatValue(value, minDigit, maxDigit) + "M" + unit;
            }
            return formatValue(value, minDigit, maxDigit) + "K" + unit;
        }
        return formatValue(value, 0, 0) + unit;
    }

    /**
     * 获取字节大小的字符串
     * @param value
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String getBytesString(double p_value, int minDigit, int maxDigit) {
        double value = p_value;
        if (value > 1024) {
            value /= 1024;
            if (value > 1024) {
                value /= 1024;
                if (value > 1024) {
                    value /= 1024;
                    return formatValue(value, minDigit, maxDigit) + "GB";
                }
                return formatValue(value, minDigit, maxDigit) + "MB";
            }
            return formatValue(value, minDigit, maxDigit) + "KB";
        }
        return formatValue(value, 0, 0) + "B";

    }

    public static String getPeriodString(long seconds) {
        long hour = seconds / 3600;
        long minute = (seconds % 3600) / 60;
        long second = (seconds % 3600) % 60;
        String period = "";
        if (hour > 0)
            period = period + hour + I18nUtil.getInstance().getValue("Hour");
        if (minute > 0)
            period = period + minute + I18nUtil.getInstance().getValue("Minute");
        if (second > 0)
            period = period + second + I18nUtil.getInstance().getValue("Second");
        return period;
    }

    public static String getPeriodByMS(long ms) {
        if (ms == 0) {
            return ("0ms");
        }
        long hour = ms / 3600000;
        long ret = ms % 3600000;
        long minute = ret / 60000;
        ret %= 60000;
        long second = ret / 1000;
        long mSecond = ret % 1000;
        String period = "";
        if (hour > 0) {
            period += hour + "h";
        }

        if (minute > 0) {
            period += minute + "m";
        }

        if (second > 0) {
            period += second + "s";
        }
        if (mSecond > 0) {
            period += mSecond + "ms";
        }
        return period;
    }

    /**
     * 从i18n文件中读取的"\n"符不再是一个字符,所以需要替换,将读取出来的字符串转成有换行符的合法串
     * @param str
     * @return
     */
    public static String getNewLineString(String p_str) {
        String str = p_str;
        if (str == null) {
            return null;
        }

        byte[] x = { 92, 110 }; // 从i18n文件中读取的"\n"的byte值
        String newline = new String(x);
        int idx = str.indexOf(newline);
        String tmp = "";
        while (idx > 0) {
            tmp = str.substring(0, idx) + "\n" + str.substring(idx + 2);
            str = tmp;
            idx = str.indexOf(newline);
        }

        return str;
    }

    /**
     * 获取当前系统时间的前n个时刻的时间 例:传入1,当前系统时间为(2007-10-11 10:12:12 的毫秒数表示) 返回时间为 (2007-10-11 9:45:00 的毫秒数表示)
     * @param preQuarterCount
     * @return Date==〉
     * @author wenju
     */
    public static Date getDatePreQuarter(int preQuarterCount) {
        int QUARTER_MILL = 900000;
        long currentMill = System.currentTimeMillis();
        long needReduce = currentMill % QUARTER_MILL;
        needReduce += QUARTER_MILL * preQuarterCount;
        currentMill -= needReduce;
        return new Date(currentMill);

    }

		/**
     * 获取流量字节数
     * @param value
     * @param minDigit
     * @param maxDigit
     * @return
     */
    public static String getbyteString(long bytes) {
        BigDecimal filesize  =   new  BigDecimal(bytes);
		BigDecimal gegabyte  =   new  BigDecimal( 1024 * 1024 * 1024 );
        float  returnValue  =  filesize.divide(gegabyte,  2 , BigDecimal.ROUND_UP).floatValue();
        if(returnValue>1){
           return (returnValue + "GB" );
		}
        BigDecimal megabyte  =   new  BigDecimal( 1024 * 1024 );
        returnValue  =  filesize.divide(megabyte,  2 , BigDecimal.ROUND_UP).floatValue();
        if(returnValue>1 ){
           return (returnValue + "MB" );
		}
        BigDecimal kilobyte  =   new  BigDecimal(1024);
        returnValue  =  filesize.divide(kilobyte,2,BigDecimal.ROUND_UP).floatValue();
		if(returnValue>1 ){
        return (returnValue + "KB" );
		}
		return (bytes + "B");
    }

	 /**
     * 格式化Double(保留位,非四舍五入)
     * @param number
     * @param maxDigit
     * @return
     */
    public static String formatdouble(double ratio,int maxDigit){
		String ratiostr=String.valueOf(ratio);
		ratiostr=ratiostr.replace('.',',');
		String Rate=ratiostr;
		String[] ratiolist=ratiostr.split(",");
		if(maxDigit>0){
		if(ratiolist.length>1){
			if(ratiolist[1].length()>=maxDigit){
				Rate=ratiolist[0]+"."+ratiolist[1].substring(0,maxDigit);
			}else{
				String str="";
				for(int i=ratiolist[1].length();i 

你可能感兴趣的:(ip地址,子网掩码,日期转换相关工具方法)