All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yixan.tools.common.util.ConvertUtil Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
package com.yixan.tools.common.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * 格式转换工具
 *
 * @author zhaohuihua
 * @version V1.0 2015年12月21日
 */
public abstract class ConvertUtil {

    @SuppressWarnings("unchecked")
    public static  T[] toArray(List list) {
        return list == null ? null : (T[]) list.toArray();
    }

    @SafeVarargs
    public static  List toList(T... array) {
        return array == null ? null : Arrays.asList(array);
    }

    /**
     * 对象转换为字符串
* 与String.valueOf()的区别是如果对象为null则返回null * * @param object 对象 * @return 字符串 */ public static String toString(Object object) { return object == null ? null : String.valueOf(object); } /** * 转换为数字 * * @param value 源字符串, 支持乘法 * @return 数字 */ public static int toInteger(String value) { return (int) toLong(value); } /** * 转换为数字 * * @param value 源字符串, 支持乘法 * @return 数字 */ public static long toLong(String value) throws NumberFormatException { if (VerifyUtil.isBlank(value)) { return 0; } value = value.trim(); if (StringUtil.isDigit(value)) { return Long.valueOf(value); } if (value.contains("*")) { Pattern ptn = Pattern.compile("\\*"); String[] values = ptn.split(value); long number = 1; boolean success = true; for (String string : values) { string = string.trim(); if (VerifyUtil.isNotBlank(string) && StringUtil.isDigit(string)) { number *= Long.valueOf(string); } else { success = false; } } if (success) { return number; } } throw new NumberFormatException(value); } /** * 转换为持续字符串
* 8000=00:00:08
* 488000=00:08:08
* 11288000=03:08:08
* 97688000=1天03:08:08
* 31536000000=365天00:00:00
* * @author zhaohuihua * @param time 持续时间 * @return 持续字符串 */ public static String toDuration(long time) { long day = 24 * 60 * 60 * 1000; SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss", Locale.US); fmt.setTimeZone(TimeZone.getTimeZone("GMT+0")); String string = fmt.format(new Date(time)); if (time > day) { string = (time / day) + "天" + string; } return string; } /** * 转换为Byte描述字符串 * * @author zhaohuihua * @param size B * @return B/KB/MB/GB */ public static String toByteString(long size) { double kb = 1024.0; double mb = kb * kb; double gb = mb * kb; DecimalFormat df = new DecimalFormat("0.##"); if (size < kb) { return df.format(size) + "B"; } else if (size < mb) { return df.format(size / kb) + "KB"; } else if (size < gb) { return df.format(size / mb) + "MB"; } else { return df.format(size / gb) + "GB"; } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy