您的位置:首页 > 编程语言 > Java开发

Java笔记17:JAVA常用函数

2016-08-04 00:00 316 查看
**

* 根据传入的格式获取日期

*

* @param format

* 如:YYYYMMDD || MM/dd/yyyy, hh:mm:ss

* @return 字符串的日期

*/

public String getSysDate(String format) {

String dateStr = "";

try {

Format formatter;

Date date = new Date();

formatter = new SimpleDateFormat(format);

dateStr = formatter.format(date);

} catch (Exception e) {

System.out.println(e);

}

return dateStr;

}

/**

* 根据传入的格式获取日期

*

* @param format

* 如:YYYYMMDD || MM/dd/yyyy, hh:mm:ss

* @return 字符串的日期

*/

public String getFormatDate(Date date, String format) {

String dateStr = "";

try {

Format formatter;

formatter = new SimpleDateFormat(format);

dateStr = formatter.format(date);

} catch (Exception e) {

System.out.println(e);

}

return dateStr;

}

/**

* 获取分割后的字符串数组信息

*

* @param Str

* @param Split

* @return 字符串数组

*/

public String[] getSplit(String Str, String Split) {

return Str.split(Split);

}

/**

* 把字符串转换成指定的日期格式

*

* @param str

* @param format

* @return

*/

public Date Convert(String str, String format) {

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);

try {

java.util.Date d = sdf.parse(str);

return d;

} catch (Exception ex) {

ex.printStackTrace();

return null;

}

}

/**

* 获取月的天数

*

* @param year

* @param month

* @return

*/

public static int getdays(String year, String month) {

int yearInt = Integer.parseInt(year);

int monthInt = Integer.parseInt(month);

int monthdays = 31;

switch (monthInt) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12: {

monthdays = 31;

break;

}

case 2: {

if (isLeapyear(yearInt)) {

monthdays = 29;

} else {

monthdays = 28;

}

break;

}

case 4:

case 6:

case 9:

case 11: {

monthdays = 30;

break;

}

}

return monthdays;

}

/**

* 判断闰年

*

* @param year

* @return

*/

public static boolean isLeapyear(int year) {

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {

return true;

} else {

return false;

}

}

/**

* 判断某天是星期几

*

* @param strDate

* @return 0 表示是星期天

*/

public static int getWeekByDate(String strDate) {

int dayOfWeek = 0;

try {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();

Date date = new Date();

date = sdf.parse(strDate);

calendar.setTime(date);

dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

} catch (Exception e) {

e.printStackTrace();

}

return dayOfWeek - 1;

}

/**

* 判断字符串是不是数字

*

* @param str

* @return

*/

public static boolean isNumeric(String str) {

Pattern pattern = Pattern.compile("[0-9]*");

Matcher isNum = pattern.matcher(str);

if (!isNum.matches()) {

return false;

}

return true;

}

/**

* 获得距给定日期countday的字符串格式

*

* @param date

* @param countday

* @param flag

* 为true表示日期前,为false表示日期后

* @return YYYY-MM-DD

*/

public String getDateString(Date date, int countday, boolean flag) {

String datestr = "";

if (flag) {

datestr = getFormatDate(new Date((new Date()).getTime() - countday

* 24 * 60 * 60 * 1000l), "yyyy-MM-dd");

} else {

datestr = getFormatDate(new Date((new Date()).getTime() + countday

* 24 * 60 * 60 * 1000l), "yyyy-MM-dd");

}

return datestr;

}

/***************************************************************************

* 根据两个时间判断时间差

* @throws ParseException

* @throws ParseException

**************************************************************************/

public Long getDateDifference(Date date1,Date date2) throws ParseException {

// Date date1 = new SimpleDateFormat("yyyy-mm-dd").parse("2008-3-31");

// Date date2 = new SimpleDateFormat("yyyy-mm-dd").parse("2008-3-30");

// 日期相减得到相差的日期

long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000) > 0 ? (date1

.getTime() - date2.getTime())

/ (24 * 60 * 60 * 1000)

: (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);

return day;

}

/***************************************************************************

* 根据两个时间来判断时间的差值

* @param days

* @return

*/

public Long getDateDifference1(Date date1,Date date2) throws ParseException {

// 日期相减得到相差的日期

long day = (date1.getTime() - date2.getTime())/ (24 * 60 * 60 * 1000);

return day;

}

/***************************************************************************

* 返回当前时间的一个时间差时间

* @param days

* @return

*/

public static String Ds(int days) {

SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();

int day = calendar.get(Calendar.DAY_OF_YEAR);

calendar.set(Calendar.DAY_OF_YEAR, day - days);

Date cc = calendar.getTime();

return form.format(cc);

}

/*************************************************************************

* 获取系统当前时间

*/

public static Date getSystemDate(){

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

Date date = new Date();

try {

return new SimpleDateFormat("yyyy-mm-dd").parse(sf.format(date));

} catch (ParseException e) {

}

return null;

}

/**

* 判断是否为整数

*

* @param str 传入的字符串

* @return 是整数返回true,否则返回false

*/

public static boolean isInteger(String str) {

Pattern pattern = Pattern.compile("^[-//+]?[//d]*$");

return pattern.matcher(str).matches();

}

/**

* 判断是否为浮点数,包括double和float

*

* @param str 传入的字符串

* @return 是浮点数返回true,否则返回false

*/

public static boolean isDouble(String str) {

Pattern pattern = Pattern.compile("^[-//+]?[.//d]*$");

return pattern.matcher(str).matches();

}

/**

* 判断输入的字符串是否符合Email样式.

*

* @param str 传入的字符串

* @return 是Email样式返回true,否则返回false

*/

public static boolean isEmail(String str) {

Pattern pattern = Pattern.compile("^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$");

return pattern.matcher(str).matches();

}

/**

* 判断输入的字符串是否为纯汉字

*

* @param str 传入的字符窜

* @return 如果是纯汉字返回true,否则返回false

*/

public static boolean isChinese(String str) {

Pattern pattern = Pattern.compile("[/u0391-/uFFE5]+$");

return pattern.matcher(str).matches();

}

/**

* 是否为空白,包括null和""

*

* @param str

* @return

*/

public static boolean isBlank(String str) {

return str == null || str.trim().length() == 0;

}

/**

* 判断是否为质数

*

* @param x

* @return

*/

public static boolean isPrime(int x) {

if (x <= 7) {

if (x == 2 || x == 3 || x == 5 || x == 7)

return true;

}

int c = 7;

if (x % 2 == 0)

return false;

if (x % 3 == 0)

return false;

if (x % 5 == 0)

return false;

int end = (int) Math.sqrt(x);

while (c <= end) {

if (x % c == 0) {

return false;

}

c += 4;

if (x % c == 0) {

return false;

}

c += 2;

if (x % c == 0) {

return false;

}

c += 4;

if (x % c == 0) {

return false;

}

c += 2;

if (x % c == 0) {

return false;

}

c += 4;

if (x % c == 0) {

return false;

}

c += 6;

if (x % c == 0) {

return false;

}

c += 2;

if (x % c == 0) {

return false;

}

c += 6;

}

return true;

}

/**

* 人民币转成大写

*

* @param value

* @return String

*/

public static String hangeToBig(double value)

{

char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示

char[] vunit = { '万', '亿' }; // 段名表示

char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示

long midVal = (long) (value * 100); // 转化成整形

String valStr = String.valueOf(midVal); // 转化成字符串

String head = valStr.substring(0, valStr.length() - 2); // 取整数部分

String rail = valStr.substring(valStr.length() - 2); // 取小数部分

String prefix = ""; // 整数部分转化的结果

String suffix = ""; // 小数部分转化的结果

// 处理小数点后面的数

if (rail.equals("00"))

{ // 如果小数部分为0

suffix = "整";

}

else

{

suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来

}

// 处理小数点前面的数

char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组

char zero = '0'; // 标志'0'表示出现过0

byte zeroSerNum = 0; // 连续出现0的次数

for (int i = 0; i < chDig.length; i++)

{ // 循环处理每个数字

int idx = (chDig.length - i - 1) % 4; // 取段内位置

int vidx = (chDig.length - i - 1) / 4; // 取段位置

if (chDig[i] == '0')

{ // 如果当前字符是0

zeroSerNum++; // 连续0次数递增

if (zero == '0')

{ // 标志

zero = digit[0];

}

else if (idx == 0 && vidx > 0 && zeroSerNum < 4)

{

prefix += vunit[vidx - 1];

zero = '0';

}

continue;

}

zeroSerNum = 0; // 连续0次数清零

if (zero != '0')

{ // 如果标志不为0,则加上,例如万,亿什么的

prefix += zero;

zero = '0';

}

prefix += digit[chDig[i] - '0']; // 转化该数字表示

if (idx > 0)

prefix += hunit[idx - 1];

if (idx == 0 && vidx > 0)

{

prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿

}

}

if (prefix.length() > 0)

prefix += '圆'; // 如果整数部分存在,则有圆的字样

return prefix + suffix; // 返回正确表示

}

/**

* 全角字符转半角字符

*

* @param QJStr

* @return String

*/

public static final String QJToBJChange(String QJStr)

{

char[] chr = QJStr.toCharArray();

String str = "";

for (int i = 0; i < chr.length; i++)

{

chr[i] = (char) ((int) chr[i] - 65248);

str += chr[i];

}

return str;

}

/**

* 去掉字符串中重复的子字符串

*

* @param str

* @return String

*/

private static String removeSameString(String str)

{

Set<String> mLinkedSet = new LinkedHashSet<String>();

String[] strArray = str.split(" ");

StringBuffer sb = new StringBuffer();

for (int i = 0; i < strArray.length; i++)

{

if (!mLinkedSet.contains(strArray[i]))

{

mLinkedSet.add(strArray[i]);

sb.append(strArray[i] + " ");

}

}

System.out.println(mLinkedSet);

return sb.toString().substring(0, sb.toString().length() - 1);

}

/**

* 根据指定方法的参数去构造一个新的对象的拷贝并将他返回

* @param obj 原始对象

* @return 新对象

* @throws NoSuchMethodException

* @throws InvocationTargetException

* @throws IllegalAccessException

* @throws InstantiationException

* @throws SecurityException

* @throws IllegalArgumentException

*/

@SuppressWarnings("unchecked")

public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,

InvocationTargetException, NoSuchMethodException

{

//获得对象的类型

Class classType = obj.getClass();

//通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法

Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});

//获得对象的所有属性

Field[] fields = classType.getDeclaredFields();

for(int i = 0; i < fields.length; i++)

{

//获取数组中对应的属性

Field field = fields[i];

String fieldName = field.getName();

String stringLetter = fieldName.substring(0, 1).toUpperCase();

//获得相应属性的getXXX和setXXX方法名称

String getName = "get" + stringLetter + fieldName.substring(1);

String setName = "set" + stringLetter + fieldName.substring(1);

//获取相应的方法

Method getMethod = classType.getMethod(getName, new Class[]{});

Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});

//调用源对象的getXXX()方法

Object value = getMethod.invoke(obj, new Object[]{});

//调用拷贝对象的setXXX()方法

setMethod.invoke(objectCopy, new Object[]{value});

}

return objectCopy;

}

//过滤特殊字符

public static String encoding(String src){

if (src==null)

return "";

StringBuilder result=new StringBuilder();

if (src!=null){

src=src.trim();

for (int pos=0;pos<src.length();pos++){

switch(src.charAt(pos)){

case '/"':result.append(""");break;

case '<':result.append("<");break;

case '>':result.append(">");break;

case '/'':result.append("'");break;

case '&':result.append("&");break;

case '%':result.append("&pc;");break;

case '_':result.append("&ul;");break;

case '#':result.append("&shap;");break;

case '?':result.append("&ques;");break;

default:result.append(src.charAt(pos));break;

}

}

}

return result.toString();

}

//反过滤特殊字符

public static String decoding(String src){

if (src==null)

return "";

String result=src;

result=result.replace(""", "/"").replace("'", "/'");

result=result.replace("<", "<").replace(">", ">");

result=result.replace("&", "&");

result=result.replace("&pc;", "%").replace("&ul", "_");

result=result.replace("&shap;", "#").replace("&ques", "?");

return result;

}

// toUtf8String将文件名转成GBK后再附到ContentDisposition

public static String toUtf8String(String s) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < s.length(); i++) {

char c = s.charAt(i);

if (c >= 0 && c <= 255) {

sb.append(c);

} else {

byte[] b;

try {

b = Character.toString(c).getBytes("utf-8");

} catch (Exception ex) {

System.out.println(ex);

b = new byte[0];

}

for (int j = 0; j < b.length; j++) {

int k = b[j];

if (k < 0)

k += 256;

sb.append("%" + Integer.toHexString(k).toUpperCase());

}

}

}

return sb.toString();

}

/**

* 对字节流进行GBK解码

*

* @param byteBuffer

* @return

*/

public static String decode(ByteBuffer byteBuffer) {

Charset charset = Charset.forName("ISO-8859-1");

CharsetDecoder decoder = charset.newDecoder();

try {

CharBuffer charBuffer = decoder.decode(byteBuffer);

return new String(charBuffer.toString().getBytes("ISO8859_1"),

"GBK").trim();

} catch (Exception e) {

return null;

}

}

//实现百分比

public String myPercent(int y, int z) {

String baifenbi = "";// 接受百分比的值

double baiy = y * 1.0;

double baiz = z * 1.0;

double fen = baiy / baiz;

// NumberFormat nf = NumberFormat.getPercentInstance(); 注释掉的也是一种方法

// nf.setMinimumFractionDigits( 2 ); 保留到小数点后几位

DecimalFormat df1 = new DecimalFormat("##.00%"); // ##.00%

// 百分比格式,后面不足2位的用0补齐

// baifenbi=nf.format(fen);

baifenbi = df1.format(fen);

return baifenbi;

}

正则表达式用于字符串处理、表单验证等场合,实用高效。现将一些常用的表达式收集于此,以备不时之需。

匹配中文字符的正则表达式: [/u4e00-/u9fa5]

评注:匹配中文还真是个头疼的事,有了这个表达式就好办了

匹配双字节字符(包括汉字在内):[^/x00-/xff]

评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)

匹配空白行的正则表达式:/n/s*/r

评注:可以用来删除空白行

匹配HTML标记的正则表达式: <(/S*?)[^>]*>.*? <//1> <.*? />

评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力

匹配首尾空白字符的正则表达式:^/s* /s*$

评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式

匹配Email地址的正则表达式:/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*

评注:表单验证时很实用

匹配网址URL的正则表达式:[a-zA-z]+://[^/s]*

评注:网上流传的版本功能很有限,上面这个基本可以满足需求

匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$

评注:表单验证时很实用

匹配国内电话号码:/d{3}-/d{8} /d{4}-/d{7}

评注:匹配形式如 0511-4405222 或 021-87888822

匹配腾讯QQ号:[1-9][0-9]{4,}

评注:腾讯QQ号从10000开始

匹配中国邮政编码:[1-9]/d{5}(?!/d)

评注:中国邮政编码为6位数字

匹配***:/d{15} /d{18}

评注:中国的***为15位或18位

匹配ip地址:/d+/./d+/./d+/./d+

评注:提取ip地址时有用

匹配特定数字:

^[1-9]/d*$    //匹配正整数

^-[1-9]/d*$   //匹配负整数

^-?[1-9]/d*$   //匹配整数

^[1-9]/d* 0$  //匹配非负整数(正整数 + 0)

^-[1-9]/d* 0$   //匹配非正整数(负整数 + 0)

^[1-9]/d*/./d* 0/./d*[1-9]/d*$   //匹配正浮点数

^-([1-9]/d*/./d* 0/./d*[1-9]/d*)$  //匹配负浮点数

^-?([1-9]/d*/./d* 0/./d*[1-9]/d* 0?/.0+ 0)$  //匹配浮点数

^[1-9]/d*/./d* 0/./d*[1-9]/d* 0?/.0+ 0$   //匹配非负浮点数(正浮点数 + 0)

^(-([1-9]/d*/./d* 0/./d*[1-9]/d*)) 0?/.0+ 0$  //匹配非正浮点数(负浮点数 + 0)

评注:处理大量数据时有用,具体应用时注意修正

匹配特定字符串:

^[A-Za-z]+$  //匹配由26个英文字母组成的字符串

^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串

^[a-z]+$  //匹配由26个英文字母的小写组成的字符串

^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串

^/w+$  //匹配由数字、26个英文字母或者下划线组成的字符串

评注:最基本也是最常用的一些表达式

String.split()方法中,有时需要特殊字符,见下:

/**

* 点的转义:. ==> //u002E

美元符号的转义:$ ==> //u0024

乘方符号的转义:^ ==> //u005E

左大括号的转义:{ ==> //u007B

左方括号的转义:[ ==> //u005B

左圆括号的转义:( ==> //u0028

竖线的转义:| ==> //u007C

右圆括号的转义:) ==> //u0029

星号的转义:* ==> //u002A

加号的转义:+ ==> //u002B

问号的转义:? ==> //u003F

反斜杠的转义:/ ==> //u005C

竖线: | ==>//u007C

* */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  public 字符串 return Java