1. 设置几天前日期

private Date getDateDynamicDaysAgo(Date startDate, int days) {Calendar cal = Calendar.getInstance();cal.setTime(startDate);cal.add(Calendar.DATE, days);Date today30 = cal.getTime();return today30;}

2.日期差多少天

/*** 计算两个日期之间相差的天数* * @param smdate*            较小的时间* @param bdate*            较大的时间* @return 相差天数* @throws ParseException*/public static int daysBetween(Date smdate, Date bdate)throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");smdate = sdf.parse(sdf.format(smdate));bdate = sdf.parse(sdf.format(bdate));Calendar cal = Calendar.getInstance();cal.setTime(smdate);long time1 = cal.getTimeInMillis();cal.setTime(bdate);long time2 = cal.getTimeInMillis();long between_days = (time2 - time1) / (1000 * 3600 * 24);return Integer.parseInt(String.valueOf(between_days));}/*** 字符串的日期格式的计算*/public static int daysBetween(String smdate, String bdate)throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Calendar cal = Calendar.getInstance();cal.setTime(sdf.parse(smdate));long time1 = cal.getTimeInMillis();cal.setTime(sdf.parse(bdate));long time2 = cal.getTimeInMillis();long between_days = (time2 - time1) / (1000 * 3600 * 24);return Integer.parseInt(String.valueOf(between_days));}

另一种但没上面效率高

369627
daysDiff : 62
369627
daysBetween : 0

public static int daysDiff(Date smdate, Date  bdate)throws Exception{Calendar calendar = Calendar.getInstance();calendar.setTime(smdate);int day1 = calendar.get(Calendar.DAY_OF_YEAR);int year1 = calendar.get(Calendar.YEAR);Calendar calendar2 = Calendar.getInstance();calendar2.setTime(bdate);int day2 = calendar2.get(Calendar.DAY_OF_YEAR);int year2 = calendar2.get(Calendar.YEAR);int yeardays = 0;if(year1 < year2){for (int year = year1; year < year2; year++) {Calendar yearLastDate = Calendar.getInstance();yearLastDate.setTime(parseDate(""+year+ "-12-31", "yyyy-MM-dd"));yeardays += yearLastDate.get(Calendar.DAY_OF_YEAR);}}else{for (int year = year2; year < year1; year++) {Calendar yearLastDate = Calendar.getInstance();yearLastDate.setTime(parseDate(""+year+ "-12-31", "yyyy-MM-dd"));yeardays += yearLastDate.get(Calendar.DAY_OF_YEAR);}}if(year1 < year2){yeardays = yeardays * -1;}return day1 - day2 + yeardays;}public static final Locale DATE_lOCALE = new Locale("en", "US");public static final String DATE_PATTERN = "yyyy-MM-dd";public static Date parseDate(String str) throws Exception{Date dt = parseDate(str, DATE_PATTERN);return dt;}public static Date parseDate(String str, String pattern) throws Exception{Date dt = parseDate(str, pattern, DATE_lOCALE);return dt;}public static Date parseDate(String str, String pattern, Locale locale) throws Exception{Date dt = parseCoreDate(str, pattern, locale);return dt;}private static Date parseCoreDate(String str, String pattern, Locale locale) throws Exception{Date dt = null;try {if (StringUtils.isBlank(pattern)) {throw new Exception("Error while converting string to date.");}if (null == locale) {throw new Exception("Error while converting string to date.");}SimpleDateFormat sdf = null;sdf = new SimpleDateFormat(pattern, locale);sdf.setLenient(false);dt = sdf.parse(str);} catch (Exception e) {throw new Exception("Error while converting string to date.");}return dt;}

3.字符串替用

ClassLoader classLoader = getClass().getClassLoader();String body=StringUtil.read(classLoader, "email/****.tmpl");   body = StringUtil.replace(body,new String[] {"[$TITLE$]", "[$FROM_NAME$]", "[$TO_NAME$]"},new String[] { subject,fromName,toName});body = StringUtil.replace(body,"[$CONTENT$]",content);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>[$TITLE$]</title>        </head><body>Dear [$TO_NAME$],<br /><br />[$CONTENT$]<br /><br /></body>
</html>

4.星期几的Util

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;public class WeekDayUtil {public enum WeekDays {Day1(1,"Day 1"),  //0b0000001Day2(2,"Day 2"),  //0b0000010Day3(4,"Day 3"),  //0b0000100Day4(8,"Day 4"),  //0b0001000Day5(16,"Day 5"), //0b0010000Day6(32,"Day 6"), //0b0100000Day7(64,"Day 7"); //0b1000000private int value;private String name;WeekDays(int val, String nam) {value = val;name = nam;}public int getValue() {return value;}public String getName() {return name;}}public static int encodeList(List<WeekDays> set) {int ret = 0;for (WeekDays val : set) {ret |= 1 << val.ordinal();}return ret;}public static List<WeekDays> decodeToList(int encoded) {List<WeekDays> ret = new ArrayList<WeekDays>();for (WeekDays val : EnumSet.allOf(WeekDays.class)) {if((encoded & val.getValue()) != 0) {ret.add(val);}}return ret;}public static boolean isDaySelected(int value, WeekDays d) {boolean match = false;if((value & d.getValue()) != 0) { match = true; }return match;}
}

5.load property file to Json Object

<span style="white-space:pre">  </span>//method to convert property file to JSON objectpublic static String convertPropertiesFileToJSONString(Properties pro ){String itemsJSON = "";Object[] keySet = pro.keySet().toArray();//System.out.println(keySet.length);for (Object key:keySet) {//System.out.println(key);itemsJSON += ",'" +key.toString() + "':'"+  pro.getProperty((String)key) + "'";}if (!itemsJSON.isEmpty())itemsJSON = itemsJSON.substring(1);itemsJSON ="{" + itemsJSON +  "}";_log.info(itemsJSON);return itemsJSON;}

6.比较两个日期

public static int compareDate(Date date1, Date date2) {if (date1.getYear()>date2.getYear())return 1;else if (date1.getYear() <date2.getYear())return -1;else if (date1.getMonth() >date2.getMonth())return 1;else if (date1.getMonth() <date2.getMonth())return -1;if (date1.getDate()>date2.getDate())return 1;else if (date1.getDate() <date2.getDate())return -1;return 0;}

7.计算年龄

 public static int calculateAge(Date birthday) {int age = 0;if (birthday != null) {Calendar dob = Calendar.getInstance();Calendar today = Calendar.getInstance();dob.setTime(birthday);age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);if (today.get(Calendar.DAY_OF_YEAR) <= dob.get(Calendar.DAY_OF_YEAR)) {age--;}}return age;}

8.Format Double to #.##

public static double formatDoubleValue(double value){DecimalFormat twoDForm = new DecimalFormat("#.##");return Double.valueOf(twoDForm.format(value));}

9,限制图片格式

 public static boolean isStrickImage(UploadedFile imageFile) {if (imageFile == null)return false;String contentType = imageFile.getContentType().toLowerCase();boolean isImage = false;if (contentType.contains("gif")) {isImage = strickModeImage(imageFile, "gif");} else if (contentType.contains("png")) {isImage = strickModeImage(imageFile, "png");} else if (contentType.contains("bmp")) {isImage = strickModeImage(imageFile, "bmp");} else if (contentType.contains("jpg")) {isImage = strickModeImage(imageFile, "jpg");} else if (contentType.contains("jpeg")) {isImage = strickModeImage(imageFile, "jpeg");}return isImage;}private static boolean strickModeImage(UploadedFile imageFile,String imageType) {if (imageFile == null || imageType == null) {return false;}InputStream is = null;try {imageType = imageType.toLowerCase();is = imageFile.getInputStream();String beginStr = null;if (imageType.equals("jpg") || imageType.equals("jpeg")) {beginStr = "FFD8FF";} else if (imageType.equals("png")) {beginStr = "89504E47";} else if (imageType.equals("gif")) {beginStr = "47494638";} else if (imageType.equals("bmp")) {beginStr = "424D";}if (beginStr == null) {return false;}byte[] b = new byte[beginStr.length() / 2];is.read(b, 0, b.length);String headStr = bytesToHexString(b);if (beginStr.equals(headStr)) {return true;} else {return false;}} catch (Exception e) {e.printStackTrace();return false;} finally {try {is.close();} catch (Exception e) {e.printStackTrace();}}}

10.String 操作

    public static boolean containsOnlyNumbers(String str) {// it can't contain only numbers if it's null or empty...if (str == null || str.length() == 0) {return false;}for (int i = 0; i < str.length(); i++) {// if we find a non-digit character we return false.if (!Character.isDigit(str.charAt(i)))return false;}return true;}public static boolean checkPostalCode(String postal) {Pattern pattern = Pattern.compile("\\d{1,6}");Matcher matcher = pattern.matcher(postal);if (!matcher.matches())return false;elsereturn true;}public static boolean checkMobileNo(String mobileNo) {if(isEmpty(mobileNo)){return true;}Pattern pattern = Pattern.compile("[0-9]{1,12}");Matcher matcher = pattern.matcher(mobileNo);if (matcher.matches())return false;elsereturn true;}

11.password 生成

public class PasswordUtil {public PasswordUtil() {super();}private static final Logger logger = LoggerFactory.getLogger(PasswordUtil.class);// generate 8 characters random password...public static String newPassword(){String password = "";String alphaUp = "abcdefghijklmnopqrstuvwxyz";String alphaLow = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";String numeric = "0987654321";//String special = "!@#_*$-+?<>=";String special = "!@_-+?=";password += RandomStringUtils.random(2,alphaUp);password += RandomStringUtils.random(2,numeric);password += RandomStringUtils.random(2,special);password += RandomStringUtils.random(2,alphaLow);List<Character> characters = new ArrayList<Character>();  for(char c : password.toCharArray()) {  characters.add(c);  }  Collections.shuffle(characters);  StringBuilder sb = new StringBuilder();  for(char c : characters) {  sb.append(c);  }  password = sb.toString();return password;}public static boolean validatePassword(String password){boolean result = true;//1.) must be at least 8 charactersif(password.length() < 8){logger.info("Length of password is "+password.length()+" which is less than 8");return false;}//2.) must have at least one numeric characterif(!password.matches(".*\\d.*")){logger.info("Password does not contain any numeric character");return false;}// check for alphabet also?//3.) must have at least one numeric characterif(!password.matches(".*?\\p{Punct}.*")){logger.info("Password does not contain any special character");return false;}//4.) must have at least one lowercase characterif(!password.matches(".*[a-z].*")){logger.info("Password does not contain lowercase character");return false;}return result;}}

项目中常用的Util方法相关推荐

  1. VB的一些项目中常用的通用方法-一般用于验证类

    1.VB的一些项目中常用的通用方法: ' 设置校验键盘输入值,数字 Public Function kyd(key As Integer) As Integer '20060728 Dim mycha ...

  2. 统计计量 | 统计学中常用的数据分析方法汇总

    来源:数据Seminar本文约10500字,建议阅读15+分钟 统计学中常用的数据分析方法汇总. Part1描述统计 描述统计是通过图表或数学方法,对数据资料进行整理.分析,并对数据的分布状态.数字特 ...

  3. 关于mysql的项目_项目中常用的MySQL 优化

    本文我们来谈谈项目中常用的MySQL优化方法,共19条,具体如下: 一.EXPLAIN 做MySQL优化,我们要善用EXPLAIN查看SQL执行计划. 下面来个简单的示例,标注(1.2.3.4.5)我 ...

  4. 乐鑫esp8266学习rtos3.0笔记第9篇:整理分享那些我在项目中常用的esp8266 rtos3.0版本的常见驱动,Button按键长短按、PWM平滑调光等。(附带demo)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个"hello ...

  5. 项目中常用的MySQL优化你知道多少?

    项目中常用的MySQL优化 文章目录 项目中常用的MySQL优化 前言 一.mysql优化是什么? 二.优化步骤 1.EXPLAIN 2.SQL语句中IN包含的值不应太多 3.SELECT语句务必指明 ...

  6. Android项目中常用的工具类集(史上最全整理)

    如果你是一名有经验的Android开发者,那么你一定积累了不少的工具类,这些工具类是帮助我们快速开发的基础.如果你是新手,那么有了这些辅助类,可以让你的项目做起来更加的简单. 下面介绍一个在GitHu ...

  7. 5种JavaScript中常用的排序方法

    5种JavaScript中常用的排序方法 01.冒泡排序 通过相邻数据元素的交换,逐步将待排序序列变为有序序列,如果前面的数据大于后面的数据,就将两值进行交换,将数据进行从小到大的排序,这样对数组的第 ...

  8. 深度学习中常用的误差方法

    深度学习中常用的误差方法有: 标准差(Standard Deviation): 标准差也叫均方差,是方差的算术平方根,反应数据的离散程度 ,标准差越小,数据偏离平均值越小,反之亦然 . 公式为: py ...

  9. java 获取sqlsession_获取Java的MyBatis框架项目中的SqlSession的方法

    从XML中构建SqlSessionFactory从XML文件中构建SqlSessionFactory的实例非常简单.这里建议你使用类路径下的资源文件来配置. String resource = &qu ...

最新文章

  1. 【数据库】数据库基本操作
  2. 从贫困的“问题少年”到计算机博士,最后成为商界泰斗,“创业之神”吉姆•克拉克是如何走向封神之路的?...
  3. JS数组方法(forEach()、every()、reduce())
  4. 倍福TwinCAT(贝福Beckhoff)常见问题(FAQ)-人机界面HMI自锁按钮和自复位按钮如何理解(Toggle variable Tap variable)...
  5. 百度超级链XChain(1)系统架构
  6. 重学 Java 之 5种字符流读取方法
  7. sql语句中的时间查询
  8. leetcode945. 使数组唯一的最小增量(排序)
  9. 如何使create-react-app与Node Back-end API一起使用
  10. Web Audio API 入门1
  11. 提示找不到msvcr71.dll怎么办
  12. 项目中的设计模式【适配器模式】
  13. 计算机网络笔记整理(第七版)谢希仁
  14. 思科防火墙配置命令(详细命令总结归纳)
  15. MySQL项目练习2——员工信息表项目
  16. A Hierarchical Latent Variable Encoder-Decoder Model for Generating Dialogues论文笔记
  17. 模型检测--工具PRISM
  18. Universal Robot——在Gazebo中模拟UR5机器人
  19. 5.3 10篇美食类小红书爆文拆解【玩赚小红书】
  20. 关于支付账户体系研究

热门文章

  1. JVM内存不足增大运行时内存
  2. Eclipse BIRT使用之BIRT Designer篇(转)
  3. SQL 注入式攻击的终极防范
  4. strcmp函数的分析及实现
  5. 以世界杯为主题的营销活动|运营策略
  6. Missing Marketing Icon - iOS Apps must include a 1024x1024px Marketing Icon in PNG format
  7. 【Qt】Q_INIT_RESOURCE的使用
  8. html 中精灵图使用
  9. python去除Excel重复项
  10. 三重缓冲:为什么我们爱它