DateTimeUtils
日期时间相关的工具类
package com.chilli.library_common.utils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* <b>类名称:</b> DateTimeUtils <br/>
* <b>类描述:</b> 日期时间相关的工具类<br/>
* <b>创建人:</b> 林肯 <br/>
* <b>修改人:</b> 编辑人 <br/>
* <b>修改时间:</b> 2015年07月29日 下午4:16 <br/>
* <b>修改备注:</b> <br/>
*
* @version 1.0.0 <br/>
*/
public class DateTimeUtils {
/**
* 英文全称 如:2010-12-01 23:15:06
*/
private static final String FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.SSS
*/
private static final String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* 英文简写(默认)如:2010-12-01
*/
public static String FORMAT_SHORT = "yyyy-MM-dd";
/**
* 中文简写 如:2010年12月01日
*/
public static String FORMAT_SHORT_CN = "yyyy年MM月dd";
/**
* 中文全称 如:2010年12月01日 23时15分06秒
*/
public static String FORMAT_LONG_CN = "yyyy年MM月dd日 HH时mm分ss秒";
/**
* 精确到毫秒的完整中文时间
*/
public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒";
private DateTimeUtils() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获得默认的 date pattern
*/
private static String getDatePattern() {
return FORMAT_LONG;
}
/**
* 根据预设格式返回当前日期
*
* @return
*/
public static String getNow() {
return format(new Date());
}
/**
* 根据用户格式返回当前日期
*
* @param format
* @return
*/
public static String getNow(String format) {
return format(new Date(), format);
}
/**
* 使用预设格式格式化日期
*
* @param date
* @return
*/
private static String format(Date date) {
return format(date, getDatePattern());
}
/**
* 使用用户格式格式化日期
*
* @param date 日期
* @param pattern 日期格式
* @return
*/
private static String format(Date date, String pattern) {
String returnValue = "";
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern, Locale.CHINA);
returnValue = df.format(date);
}
return (returnValue);
}
/**
* 使用预设格式提取字符串日期
*
* @param strDate 日期字符串
* @return
*/
private static Date parse(String strDate) {
return parse(strDate, getDatePattern());
}
/**
* 使用用户格式提取字符串日期
*
* @param strDate 日期字符串
* @param pattern 日期格式
* @return
*/
private static Date parse(String strDate, String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern, Locale.CHINA);
try {
return df.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 在日期上增加数个整月
*
* @param date 日期
* @param n 要增加的月数
* @return
*/
public static Date addMonth(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, n);
return cal.getTime();
}
/**
* 在日期上增加天数
*
* @param date 日期
* @param n 要增加的天数
* @return
*/
public static Date addDay(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, n);
return cal.getTime();
}
/**
* 获取时间戳
*/
public static String getTimeString() {
SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL, Locale.CHINA);
Calendar calendar = Calendar.getInstance();
return df.format(calendar.getTime());
}
/**
* 获取日期年份
*
* @param date 日期
* @return
*/
public static String getYear(Date date) {
return format(date).substring(0, 4);
}
/**
* 按默认格式的字符串距离今天的天数
*
* @param date 日期字符串
* @return
*/
public static int countDays(String date) {
long t = Calendar.getInstance().getTime().getTime();
Calendar c = Calendar.getInstance();
c.setTime(parse(date));
long t1 = c.getTime().getTime();
return (int) (t / 1000 - t1 / 1000) / 3600 / 24;
}
/**
* 按用户格式字符串距离今天的天数
*
* @param date 日期字符串
* @param format 日期格式
* @return
*/
public static int countDays(String date, String format) {
long t = Calendar.getInstance().getTime().getTime();
Calendar c = Calendar.getInstance();
c.setTime(parse(date, format));
long t1 = c.getTime().getTime();
return (int) (t / 1000 - t1 / 1000) / 3600 / 24;
}
/**
* 按用户给的时间戳获取预设格式的时间
*
* @param date 时间戳
* @param pattern 预设时间格式
* @return
*/
public static String getDate(String date, String pattern) {
Date dates = new Date();
dates.setTime(Long.parseLong(date));
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(dates);
}
/**
* 3分钟前 刚刚
* 1小时前
* 今天 hh:mm
* 昨天 hh:mm
* 6-11 hh:mm
*/
public static String getDateForNew(String date,String pattern) {
long time = Long.parseLong(date);//发布时间
long currentTime = System.currentTimeMillis();//系统当前时间
long chaSeconds = (currentTime-time)/1000;//时间差 秒为单位
//格式化
Date dates = new Date();
SimpleDateFormat format = new SimpleDateFormat(pattern);//hh:mm
dates.setTime(time);
//
SimpleDateFormat formatday = new SimpleDateFormat("MM-dd hh:mm");
if(chaSeconds < 3*60){
return "刚刚";
}else if(chaSeconds < 60*60){
return "1小时前";
}else if(chaSeconds < 24*60*60){
return "1天前"+format.format(dates);
}else if(chaSeconds < 2*24*60*60){
return "2天前"+format.format(dates);
}else{
return formatday.format(dates);
}
}
/**
* 格式化时间 判断一个日期 是否为 今天、昨天
*
* @param time
* @return
*/
public static String formatDateTime(String time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
if (time == null || "".equals(time)) {
return "";
}
Date date = null;
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar current = Calendar.getInstance();
Calendar today = Calendar.getInstance(); //今天
today.set(Calendar.YEAR, current.get(Calendar.YEAR));
today.set(Calendar.MONTH, current.get(Calendar.MONTH));
today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
// Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
Calendar yesterday = Calendar.getInstance(); //昨天
yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
yesterday.set(Calendar.HOUR_OF_DAY, 0);
yesterday.set(Calendar.MINUTE, 0);
yesterday.set(Calendar.SECOND, 0);
current.setTime(date);
if (current.after(today)) {
return "今天 " + time.split(" ")[1];
} else if (current.before(today) && current.after(yesterday)) {
return "昨天 " + time.split(" ")[1];
} else {
// int index = time.indexOf("-")+1;
// return time.substring(index, time.length());
int index = time.indexOf(" ");
return time.substring(0, index);
}
}
/**
* 将UTC-0时区时间字符串转换成用户时区时间的描述.
*
* @param strUtcTime UTC-0时区的时间
* @param strInFmt 时间的输入格式
* @param strOutFmt 时间的输出格式,若为null则输出格式与输入格式相同
* @return 用户时区的时间描述.
* @throws ParseException 时间转换异常
*/
public static String getUserZoneString(final String strUtcTime,
final String strInFmt, final String strOutFmt)
throws ParseException {
if (StringUtils.isNull(strUtcTime)) {
throw new NullPointerException("参数strDate不能为空");
} else if (StringUtils.isNull(strInFmt)) {
throw new NullPointerException("参数strInFmt不能为空");
}
long lUserMillis = getUserZoneMillis(strUtcTime, strInFmt);
String strFmt = strInFmt;
if (!StringUtils.isNull(strOutFmt)) {
strFmt = strOutFmt;
}
return format(lUserMillis, strFmt);
}
/**
* 格式化时间.
*
* @param lMillis 时间参数
* @param strInFmt 时间格式
* @return 对应的时间字符串
*/
public static String format(final long lMillis, final String strInFmt) {
if (StringUtils.isNull(strInFmt)) {
throw new NullPointerException("参数strInFmt不能为空");
}
return (String) DateFormat.format(strInFmt, lMillis);
}
/**
* 将UTC-0时区时间字符串转换成用户时区时间距离1970-01-01的毫秒数.
*
* @param strUtcTime UTC-0时区的时间字符串
* @param strInFmt 时间格式
* @return 用户时区时间距离1970-01-01的毫秒数.
* @throws ParseException 时间转换异常
*/
@SuppressWarnings("deprecation")
public static long getUserZoneMillis(final String strUtcTime,
final String strInFmt) throws ParseException {
if (StringUtils.isNull(strUtcTime)) {
throw new NullPointerException("参数strUtcTime不能为空");
} else if (StringUtils.isNull(strInFmt)) {
throw new NullPointerException("参数strInFmt不能为空");
}
long lUtcMillis = parseMillis(strUtcTime, strInFmt);
Time time = new Time();
time.setToNow();
long lOffset = time.gmtoff * DateUtils.SECOND_IN_MILLIS;
long lUserZoneMillis = lUtcMillis + lOffset;
return lUserZoneMillis;
}
/**
* 转换时间格式,将字符串转换为距离1970-01-01的毫秒数.
*
* @param strDate 指定时间的字符串
* @param strInFmt 时间字符串的格式
* @return 指定时间字符串距离1970-01-01的毫秒数
* @throws ParseException 时间转换异常
*/
public static long parseMillis(final String strDate, final String strInFmt)
throws ParseException {
if (StringUtils.isNull(strDate)) {
throw new NullPointerException("参数strDate不能为空");
} else if (StringUtils.isNull(strInFmt)) {
throw new NullPointerException("参数strInFmt不能为空");
}
SimpleDateFormat sdf = new SimpleDateFormat(strInFmt,
Locale.getDefault());
Date date = sdf.parse(strDate);
return date.getTime();
}
public static String utc2BeiJingTime(String message) {
String beiJingTime = message;
if (message.contains("#")) {
String[] loginInfo = message.split("#");
if (loginInfo != null && loginInfo.length >= 3) {
try {
String utcTime = loginInfo[1];
beiJingTime = DateTimeUtils.getUserZoneString(utcTime, "HH:mm", null);
String repaceTimeStr = "#"+utcTime+"#";
beiJingTime = message.replace(repaceTimeStr,beiJingTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
return beiJingTime;
}
/**
* @param duration 秒钟
* */
public static String format(int duration){
String second = "";
String minute = "";
String time = "";
//获取到时间
int mm = duration / 60;//分
int ss = duration % 60;//秒
if (ss < 10) {
second = "0" + String.valueOf(ss);
} else {
second = String.valueOf(ss);
}
if (mm < 10) {
minute = "0" + String.valueOf(mm);
} else {
minute = String.valueOf(mm);//分钟
}
time = minute +":"+ second;
return time;
}
}
StringUtils
字符串工具类
package com.chilli.library_common.utils;
import android.content.Context;
import android.text.TextUtils;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* <b>类名称:</b> StringUtils <br/>
* <b>类描述:</b> 字符串工具类<br/>
* <b>创建人:</b> 林肯 <br/>
* <b>修改人:</b> 编辑人 <br/>
* <b>修改时间:</b> 2015年07月29日 下午2:18 <br/>
* <b>修改备注:</b> <br/>
*
* @version 1.0.0 <br/>
*/
public class StringUtils {
private StringUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断字符串是否为空或空字符
*
* @param strSource 源字符串
* @return true表示为空,false表示不为空
*/
public static boolean isNull(final String strSource) {
return strSource == null || "".equals(strSource.trim());
}
/**
* is null or its length is 0 or it is made by space
* <p>
* <pre>
* isBlank(null) = true;
* isBlank("") = true;
* isBlank(" ") = true;
* isBlank("a") = false;
* isBlank("a ") = false;
* isBlank(" a") = false;
* isBlank("a b") = false;
* </pre>
*
* @param str
* @return if string is null or its size is 0 or it is made by space, return true, else return false.
*/
public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
/**
* 获取字符串长度的安全方法
* get length of CharSequence
* <p>
* <pre>
* length(null) = 0;
* length(\"\") = 0;
* length(\"abc\") = 3;
* </pre>
*
* @param str
* @return if str is null or empty, return 0, else return {@link CharSequence#length()}.
*/
public static int size(CharSequence str) {
return str == null ? 0 : str.length();
}
/**
* null Object to empty string
* <p>
* <pre>
* nullStrToEmpty(null) = "";
* nullStrToEmpty("") = "";
* nullStrToEmpty("aa") = "aa";
* </pre>
*
* @param str
* @return
*/
public static String nullStrToEmpty(Object str) {
return (str == null ? "" : (str instanceof String ? (String) str : str.toString()));
}
/**
* 转换首字母为大写
* capitalize first letter
* <p>
* <pre>
* capitalizeFirstLetter(null) = null;
* capitalizeFirstLetter("") = "";
* capitalizeFirstLetter("2ab") = "2ab"
* capitalizeFirstLetter("a") = "A"
* capitalizeFirstLetter("ab") = "Ab"
* capitalizeFirstLetter("Abc") = "Abc"
* </pre>
*
* @param str
* @return
*/
public static String capitalizeFirstLetter(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char c = str.charAt(0);
return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : String.valueOf(Character.toUpperCase(c)) + str.substring(1);
}
/**
* 是否是Utf-8字符串
* encoded in utf-8
* <p>
* <pre>
* utf8Encode(null) = null
* utf8Encode("") = "";
* utf8Encode("aa") = "aa";
* utf8Encode("啊啊啊啊") = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
* </pre>
*
* @param str
* @return
* @throws UnsupportedEncodingException if an error occurs
*/
public static String utf8Encode(String str) {
if (!TextUtils.isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
}
}
return str;
}
/**
* 使用utf-8转码
* encoded in utf-8, if exception, return defultReturn
*
* @param str
* @param defultReturn
* @return
*/
public static String utf8Encode(String str, String defultReturn) {
if (!TextUtils.isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return defultReturn;
}
}
return str;
}
/**
* 获取<a></a>标签内的内容
* get innerHtml from href
* <p>
* <pre>
* getHrefInnerHtml(null) = ""
* getHrefInnerHtml("") = ""
* getHrefInnerHtml("mp3") = "mp3";
* getHrefInnerHtml("<a innerHtml</a>") = "<a innerHtml</a>";
* getHrefInnerHtml("<a>innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a<a>innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a href="baidu.com">innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";
* getHrefInnerHtml(" <a>innerHtml</a> ") = "innerHtml";
* getHrefInnerHtml("<a>innerHtml</a></a>") = "innerHtml";
* getHrefInnerHtml("jack<a>innerHtml</a></a>") = "innerHtml";
* getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>") = "innerHtml2";
* </pre>
*
* @param href
* @return <ul>
* <li>if href is null, return ""</li>
* <li>if not match regx, return source</li>
* <li>return the last string that match regx</li>
* </ul>
*/
public static String getHrefInnerHtml(String href) {
if (TextUtils.isEmpty(href)) {
return "";
}
String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
Matcher hrefMatcher = hrefPattern.matcher(href);
if (hrefMatcher.matches()) {
return hrefMatcher.group(1);
}
return href;
}
/**
* Html文本格式转码
* process special char in html
* <p>
* <pre>
* htmlEscapeCharsToString(null) = null;
* htmlEscapeCharsToString("") = "";
* htmlEscapeCharsToString("mp3") = "mp3";
* htmlEscapeCharsToString("mp3<") = "mp3<";
* htmlEscapeCharsToString("mp3>") = "mp3\>";
* htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4";
* htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4";
* htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4";
* </pre>
*
* @param source
* @return
*/
public static String htmlEscapeCharsToString(String source) {
return TextUtils.isEmpty(source) ? source : source.replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("&", "&").replaceAll(""", "\"");
}
/**
* 全角字符 转为为半角字符
* transform full width char to half width char
* <p>
* <pre>
* fullWidthToHalfWidth(null) = null;
* fullWidthToHalfWidth("") = "";
* fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
* fullWidthToHalfWidth("!"#$%&) = "!\"#$%&";
* </pre>
*
* @param s
* @return
*/
public static String fullWidthToHalfWidth(String s) {
if (TextUtils.isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == 12288) {
source[i] = ' ';
// } else if (source[i] == 12290) {
// source[i] = '.';
} else if (source[i] >= 65281 && source[i] <= 65374) {
source[i] = (char) (source[i] - 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}
/**
* 将半角字符转换为全角字符
* transform half width char to full width char
* <p>
* <pre>
* halfWidthToFullWidth(null) = null;
* halfWidthToFullWidth("") = "";
* halfWidthToFullWidth(" ") = new String(new char[] {12288});
* halfWidthToFullWidth("!\"#$%&) = "!"#$%&";
* </pre>
*
* @param s
* @return
*/
public static String halfWidthToFullWidth(String s) {
if (TextUtils.isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == ' ') {
source[i] = (char) 12288;
// } else if (source[i] == '.') {
// source[i] = (char)12290;
} else if (source[i] >= 33 && source[i] <= 126) {
source[i] = (char) (source[i] + 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
/**
* 判断字符串是否为空
*
* @param str null、“ ”、“null”都返回true
* @return boolean
*/
public static boolean isNullString(String str) {
return (null == str || isBlank(str.trim()) || "null".equals(str.trim()
.toLowerCase()));
}
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* 格式化字符串 如果为空,返回“”
*
* @param str
* @return String
*/
public static String formatString(String str) {
if (isNullString(str)) {
return "";
} else {
return str;
}
}
/**
* 获得文件名称
*
* @param path
* @return String
*/
public static String getFileName(String path) {
if (isNullString(path))
return null;
int bingindex = path.lastIndexOf("/");
return path.substring(bingindex + 1, path.length());
}
/**
* 获得文件名称前缀
*
* @param path
* @return String
*/
public static String getFileNamePrefix(String path) {
if (isNullString(path))
return null;
int bingindex = path.lastIndexOf("/");
int endindex = path.lastIndexOf(".");
return path.substring(bingindex + 1, endindex);
}
private static Pattern numericPattern = Pattern.compile("^[0-9\\-]+$");
/**
* 判断字符串是否是数字
*
* @param src
* @return boolean
*/
public static boolean isNumeric(String src) {
boolean return_value = false;
if (src != null && src.length() > 0) {
Matcher m = numericPattern.matcher(src);
if (m.find()) {
return_value = true;
}
}
return return_value;
}
/**
* 自动命名文件,命名文件格式如:IP地址+时间戳+三位随机数 .doc
*
* @param ip ip地址
* @param fileName 文件名
* @return String
*/
public static String getIPTimeRandName(String ip, String fileName) {
StringBuilder buf = new StringBuilder();
if (ip != null) {
String str[] = ip.split("\\.");
for (String aStr : str) {
buf.append(addZero(aStr, 3));
}
}// 加上IP地址
buf.append(getTimeStamp());// 加上日期
Random random = new Random();
for (int i = 0; i < 3; i++) {
buf.append(random.nextInt(10));// 取三个随机数追加到StringBuffer
}
buf.append(".").append(getFileExt(fileName));// 加上扩展名
return buf.toString();
}
/**
* 自动命名文件,命名文件格式如:时间戳+三位随机数 .doc
*
* @param fileName
* @return String
*/
public static String getTmeRandName(String fileName) {
return getIPTimeRandName(null, fileName);
}
public static String addZero(String str, int len) {
StringBuilder s = new StringBuilder();
s.append(str);
while (s.length() < len) {
s.insert(0, "0");
}
return s.toString();
}
/**
* 获得时间戳 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单
*
* @return String
*/
public static String getTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(new Date());
}
/**
* 获得文件扩展名
*
* @param filename
* @return String
*/
public static String getFileExt(String filename) {
int i = filename.lastIndexOf(".");// 返回最后一个点的位置
String extension = filename.substring(i + 1);// 取出扩展名
return extension;
}
/**
* 将url进行utf-8编码
*
* @param url
* @return String
*/
public static String encodeURL(String url) {
try {
return URLEncoder.encode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* 将url进行utf-8解码
*
* @param url
* @return String
*/
public static String decodeURL(String url) {
try {
return URLDecoder.decode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* 格式化日期字符串 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单
*
* @param date
* @param pattern
* @return String
*/
public static String formatDate(Date date, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
/**
* 格式化日期字符串 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单
*/
public static String formatDate(Date date) {
return formatDate(date, DEFAULT_DATE_PATTERN);
}
/**
* 获取当前时间 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单
*
* @return String
*/
public static String getDate() {
return formatDate(new Date(), DEFAULT_DATE_PATTERN);
}
/**
* 获取当前时间
*
* @return String
*/
public static String getDateTime() {
return formatDate(new Date(), DEFAULT_DATETIME_PATTERN);
}
/**
* 格式化日期时间字符串
*/
public static String formatDateTime(Date date) {
return formatDate(date, DEFAULT_DATETIME_PATTERN);
}
/**
* 格式化json格式日期
*
* @param date
* @return String
*/
@SuppressWarnings("deprecation")
public static String formatJsonDateTime(JSONObject date) {
Date result = null;
try {
result = new Date(date.getInt("year"), date.getInt("month"),
date.getInt("date"), date.getInt("hours"),
date.getInt("minutes"), date.getInt("seconds"));
} catch (Exception e) {
e.printStackTrace();
}
return result == null ? "" : formatDateTime(result);
}
/**
* 将字符串集合 变为以 separator 分割的字符串
*
* @param array 字符串集合
* @param separator 分隔符
* @return String
*/
public static String join(final ArrayList<String> array, String separator) {
StringBuilder result = new StringBuilder();
if (array != null && array.size() > 0) {
for (String str : array) {
result.append(str);
result.append(separator);
}
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
/**
* 压缩字符串
*
* @param str
* @return String
* @throws IOException
*/
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
}
/**
* 解压缩字符串
*
* @param str
* @return String
* @throws IOException
*/
public static String uncompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(
str.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString("UTF-8");
}
/**
* <b>description :</b> 去除特殊字符或将所有中文标号替换为英文标号
*
* @param input
* @return String
*/
public static String stringFilter(String input) {
if (input == null)
return null;
input = input.replaceAll("【", "[").replaceAll("】", "]")
.replaceAll("!", "!").replaceAll(":", ":");// 替换中文标号
String regEx = "[『』]"; // 清除掉特殊字符
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(input);
return m.replaceAll("").trim();
}
/**
* <b>description :</b> 半角字符转全角字符
*
* @param input
* @return String
*/
public static String ToDBC(String input) {
if (input == null)
return null;
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
return new String(c);
}
/**
* 判断字符串"oldString"是否为null
*
* @param oldString 需要判断的字符串
* @return String 如果"oldString"为null返回空值"",否则返回"oldString"
*/
public static String getString(String oldString) {
if (oldString == null || "null".equals(oldString)) {
return "";
} else {
return oldString.trim();
}
}
/**
* 将一实数转换成字符串并返回
*
* @param d 实数
* @return String
*/
public static String getString(double d) {
return String.valueOf(d);
}
/**
* 得到文件的后缀名(扩展名)
*
* @param name
* @return String 后缀名
*/
public static String getAfterPrefix(String name) throws Exception {
return name.substring(name.lastIndexOf(".") + 1, name.length());
}
/**
* 分割字符串
*
* @param values 要分割的内容
* @param limit 分隔符 例:以“,”分割
* @return String[] 返回数组,没有返回null
*/
public static String[] spilctMoreSelect(String values, String limit) {
if (isNullOrEmpty(values)) {
return null;
}
return values.trim().split(limit);
}
/**
* 将字符串数组转化为字符串
*
* @param needvalue
* @return String 返回字符串,否则返回null
*/
public static String arr2Str(String[] needvalue) {
String str = "";
if (needvalue != null) {
int len = needvalue.length;
for (int i = 0; i < len; i++) {
if (i == len - 1) {
str += needvalue[i];
} else {
str += needvalue[i] + ",";
}
}
return str;
} else {
return null;
}
}
public static int arr2int(String[] arr) {
if (arr != null && arr.length > 0) {
return Integer.parseInt(arr[1]);
}
return -1;
}
/**
* 判断字符串是否为空或空符串。
*
* @param str 要判断的字符串。
* @return String 返回判断的结果。如果指定的字符串为空或空符串,则返回true;否则返回false。
*/
public static boolean isNullOrEmpty(String str) {
return (str == null) || (str.trim().length() == 0);
}
/**
* 去掉字符串两端的空白字符。因为String类里边的trim()方法不能出现null.trim()的情况,因此这里重新写一个工具方法。
*
* @param str 要去掉空白的字符串。
* @return String 返回去掉空白后的字符串。如果字符串为null,则返回null;否则返回str.trim()。 *
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
/**
* 更具配置的string.xml 里的id,得到内容
*
* @param context
* @param id
* @return String
*/
public static String getValueById(Context context, int id) {
return context.getResources().getString(id);
}
/**
* 用于文中强制换行的处理
*
* @param oldstr
* @return String
*/
public static String replaceStr(String oldstr) {
oldstr = oldstr.replaceAll("\n", "<br>");// 替换换行
oldstr = oldstr.replaceAll("\r\n", "<br>");// 替换回车换行
oldstr = oldstr.replaceAll(" ", " " + " ");// 替换空格
return oldstr;
}
/**
* 判断是否是数字
*
* @param c
* @return boolean
*/
public static boolean isNum(char c) {
return c >= 48 && c <= 57;
}
/**
* 获得题号 例如:2.本文选自哪篇文章? 提取题号中的数字 2
*
* @param content
* @return int
*/
public static int getThemeNum(String content) {
int tnum = -1;
if (isNullOrEmpty(content))
return tnum;
int a = content.indexOf(".");
if (a > 0) {
String num = content.substring(0, a);
try {
tnum = Integer.parseInt(num);
} catch (NumberFormatException e) {
e.printStackTrace();
return tnum;
}
}
return tnum;
}
// 添加自己的字符串操作
public static String dealDigitalFlags(String str) {
String result = "";
if (str == null || str.length() < 0) {
return null;
} else {
int len = str.length();
for (int i = 0; i < len; i++) {
String tmp = str.substring(i, i + 1);
if (tmp.equals("+") || tmp.equals("*") || tmp.equals("=")) {
tmp = " " + tmp + " ";
}
result += tmp;
}
}
return result;
}
/**
* 截取序号 例如:01026---->26
*
* @param oldnum
* @return String
*/
public static String detailNum(String oldnum) {
if (isNullOrEmpty(oldnum))
return oldnum;
int newnum = Integer.parseInt(oldnum);
return newnum + ".";
}
public static String[] getStoreArr(String[] arr) throws Exception {
String temp;
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length - 1; j > i; j--) {
int a = Integer.parseInt(arr[i]);
int b = Integer.parseInt(arr[j]);
if (a > b) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
/**
* 给数字字符串排序 如:3,1,2 --->1,2,3
*
* @param str
* @return String
* @throws Exception
*/
public static String resetStoreNum(String str) {
String value = "";
try {
if (str == null || str.length() < 1)
return value;
String[] results = str.split(",");
String[] newarr = getStoreArr(results);
for (String aNewarr : newarr) {
value += aNewarr + ",";
}
value = value.substring(0, value.length() - 1);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
/**
* 判断数组中是否包含某个值
*
* @param srcValue
* @param values
* @return boolean
*/
public static boolean arrIsValue(String srcValue, String[] values) {
if (values == null) {
return false;
}
for (String value : values) {
if (value.equals(srcValue)) {
return true;
}
}
return false;
}
/**
* 获得"."之后的所有内容
*
* @param content 原字符串
* @return String
*/
public static String DeleteOriNumber(String content) {
if (content.trim().length() > 1) {
int index = content.indexOf(".");
String AfterStr = content.substring(index + 1, content.length());
return AfterStr;
} else {
return content;
}
}
/**
* GBK编码
*
* @param content
* @return String
*/
public static String convertToGBK(String content) {
if (!isEmpty(content)) {
try {
content = new String(content.getBytes(), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return content;
}
private static String trimSpaces(String IP) {// 去掉IP字符串前后所有的空格
while (IP.startsWith(" ")) {
IP = IP.substring(1, IP.length()).trim();
}
while (IP.endsWith(" ")) {
IP = IP.substring(0, IP.length() - 1).trim();
}
return IP;
}
/**
* 判断是否是一个IP
*
* @param IP
* @return boolean
*/
public static boolean isIp(String IP) {
boolean b = false;
IP = trimSpaces(IP);
if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
String s[] = IP.split("\\.");
if (Integer.parseInt(s[0]) < 255)
if (Integer.parseInt(s[1]) < 255)
if (Integer.parseInt(s[2]) < 255)
if (Integer.parseInt(s[3]) < 255)
b = true;
}
return b;
}
/**
* 将字符串转位日期类型
*
* @param sdate
* @return Date
*/
public static Date toDate(String sdate) {
try {
return dateFormater.get().parse(sdate);
} catch (ParseException e) {
return null;
}
}
/**
* 方法: distanceSize
* 描述: 计算距离
*
* @param distance 距离数 单位千米
* @return String 转换后的距离
*/
public static String distanceSize(double distance) {
if (distance < 1.0) return (int) (distance * 1000) + "m";
String dd = "0";
try {
DecimalFormat fnum = new DecimalFormat("##0.00");
dd = fnum.format(distance);
} catch (Exception e) {
e.printStackTrace();
}
return dd + "km";
}
/**
* 方法: replaceResult
* 描述: 替换结果字符串
*
* @param content
* @return String 返回类型
*/
public static String replaceResult(String content) {
if (!isEmpty(content))
content = content.replace("\\", "").replace("\"{", "{").replace("}\"", "}");
return content;
}
/**
* 方法: checkPhone
* 描述: 提取电话号码
*
* @param content
* @return ArrayList<String> 返回类型
*/
public static ArrayList<String> checkPhone(String content) {
ArrayList<String> list = new ArrayList<String>();
if (isEmpty(content)) return list;
Pattern p = Pattern.compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}");
Matcher m = p.matcher(content);
while (m.find()) {
list.add(m.group());
}
return list;
}
/**
* <p>描述:保留一位小数</p>
*
* @param value
* @return 设定文件
*/
public static String parseStr(String value) {
if (isNullString(value)) return "0.0";
DecimalFormat df = new DecimalFormat("######0.0");
double mvalue = Double.parseDouble(value);
return df.format(mvalue);
}
public static String parseStr2(String value) {
if (isNullString(value)) return "--";
DecimalFormat df = new DecimalFormat("######0.0");
double mvalue = Double.parseDouble(value);
String mStr = df.format(mvalue);
if (mStr.equals("0") || mStr.equals("0.0")) {
return "--";
}
return mStr;
}
public static String parseStr(double value) {
if (value == 0) return "0.0";
DecimalFormat df = new DecimalFormat("######0.0");
return df.format(Double.parseDouble(String.valueOf(value)));
}
/**
* 处理自动换行问题
*
* @param input 字符串
* @return 设定文件
*/
public static String ToWrap(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
return new String(c);
}
/**
* 时间显示转换
*
* @param duration 时间区间 0-59
* @param isShowZero 小于10是否显示0 如:09
* @return
*/
public static String durationShow(int duration, boolean isShowZero) {
String showStr;
if (isShowZero) {
if (duration < 10) {
showStr = "0" + String.valueOf(duration);
} else {
showStr = String.valueOf(duration);
}
} else {
showStr = String.valueOf(duration);
}
return showStr;
}
public static long fromTimeString(String s) {
if (s.lastIndexOf(".") != -1) {
s = s.substring(0, s.lastIndexOf("."));
}
String[] split = s.split(":");
if (split.length == 3) {
return Long.parseLong(split[0]) * 3600L + Long.parseLong(split[1]) * 60L + Long.parseLong(split[2]);
} else if (split.length == 2) {
return Long.parseLong(split[0]) * 60L + Long.parseLong(split[0]);
} else {
throw new IllegalArgumentException("Can\'t parse time string: " + s);
}
}
public static String toTimeString(long seconds) {
seconds = seconds / 1000;
long hours = seconds / 3600L;
long remainder = seconds % 3600L;
long minutes = remainder / 60L;
long secs = remainder % 60L;
if (hours == 0) {
return (minutes < 10L ? "0" : "") + minutes + ":" + (secs < 10L ? "0" : "") + secs;
}
return (hours < 10L ? "0" : "") + hours + ":" + (minutes < 10L ? "0" : "") + minutes + ":" + (secs < 10L ? "0" : "") + secs;
}
/**
* 是否含有表情符
* false 为含有表情符
*/
public static boolean checkFace(String checkString) {
String reg = "^([a-z]|[A-Z]|[0-9]|[\u0000-\u00FF]|[\u2000-\uFFFF]){1,}$";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(checkString.replaceAll(" ", ""));
return matcher.matches();
}
}