时间代码

时间代码Java时间日期格式转换突然忘记了时间格式怎么转换,特此做个记录//转换百分数NumberFormatnf =NumberFormat.getPercentInstance();nf.setMinimumFractionDigits(2);//设置保留小数位nf.setRou

大家好,欢迎来到IT知识分享网。时间代码

Java时间日期格式转换

突然忘记了时间格式怎么转换,特此做个记录

//转换百分数

NumberFormat nf = NumberFormat.getPercentInstance();

nf.setMinimumFractionDigits(2);//设置保留小数位

nf.setRoundingMode(RoundingMode.HALF_UP); //设置舍入模式

 

String vigourTeamVitality = nf.format(percent);

例子:
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);
sdf.format(new Date());
得到的日期格式为:2008-05-14

 

 //转换日期格式

if (CommonUtil.isNotEmpty(startTime) && CommonUtil.isNotEmpty(endTime)) {

start = DateUtil.getDate(startTime, “yyyy-MM-dd”).getTime();

end = DateUtil.getLastTimeOfDay(endTime).getTime();

}

Java时间格式转换大全

 

import java.text.*;

import java.util.Calendar;

public class VeDate {

/**

   * 获取现在时间

   *

   * @return 返回时间类型 yyyy-MM-dd HH:mm:ss

   */

public static Date getNowDate() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   String dateString = formatter.format(currentTime);

   ParsePosition pos = new ParsePosition(8);

   Date currentTime_2 = formatter.parse(dateString, pos);

   return currentTime_2;

}

/**

   * 获取现在时间

   *

   * @return返回短时间格式 yyyy-MM-dd

   */

DateFormat format1 = new SimpleDateFormat(“yyyy-MM-dd”);         

DateFormat format 2= new SimpleDateFormat(“yyyy年MM月dd日 HH时mm分ss秒”);         

Date date = null;    

String str = null;                  

            

// String转Date    

str = “2007-1-18”;          

try {    

           date = format1.parse(str);   

           data = format2.parse(str);

} catch (ParseException e) {    

           e.printStackTrace();    

}   

/**

   * 获取现在时间

   *

   * @return返回字符串格式 yyyy-MM-dd HH:mm:ss

   */

public static String getStringDate() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   String dateString = formatter.format(currentTime);

   return dateString;

}

/**

   * 获取现在时间

   *

   * @return 返回短时间字符串格式yyyy-MM-dd

   */

public static String getStringDateShort() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

   String dateString = formatter.format(currentTime);

   return dateString;

}

/**

   * 获取时间 小时:分;秒 HH:mm:ss

   *

   * @return

   */

public static String getTimeShort() {

   SimpleDateFormat formatter = new SimpleDateFormat(“HH:mm:ss”);

   Date currentTime = new Date();

   String dateString = formatter.format(currentTime);

   return dateString;

}

/**

   * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss

   *

   * @param strDate

   * @return

   */

public static Date strToDateLong(String strDate) {

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   ParsePosition pos = new ParsePosition(0);

   Date strtodate = formatter.parse(strDate, pos);

   return strtodate;

}

/**

   * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss

   *

   * @param dateDate

   * @return

   */

public static String dateToStrLong(java.util.Date dateDate) {

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   String dateString = formatter.format(dateDate);

   return dateString;

}

/**

   * 将短时间格式时间转换为字符串 yyyy-MM-dd

   *

   * @param dateDate

   * @param k

   * @return

   */

public static String dateToStr(java.util.Date dateDate) {

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

   String dateString = formatter.format(dateDate);

   return dateString;

}

/**

   * 将短时间格式字符串转换为时间 yyyy-MM-dd

   *

   * @param strDate

   * @return

   */

public static Date strToDate(String strDate) {

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

   ParsePosition pos = new ParsePosition(0);

   Date strtodate = formatter.parse(strDate, pos);

   return strtodate;

}

/**

   * 得到现在时间

   *

   * @return

   */

public static Date getNow() {

   Date currentTime = new Date();

   return currentTime;

}

/**

   * 提取一个月中的最后一天

   *

   * @param day

   * @return

   */

public static Date getLastDate(long day) {

   Date date = new Date();

   long date_3_hm = date.getTime() – 3600000 * 34 * day;

   Date date_3_hm_date = new Date(date_3_hm);

   return date_3_hm_date;

}

/**

   * 得到现在时间

   *

   * @return 字符串 yyyyMMdd HHmmss

   */

public static String getStringToday() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyyMMdd HHmmss”);

   String dateString = formatter.format(currentTime);

   return dateString;

}

/**

   * 得到现在小时

   */

public static String getHour() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   String dateString = formatter.format(currentTime);

   String hour;

   hour = dateString.substring(11, 13);

   return hour;

}

/**

   * 得到现在分钟

   *

   * @return

   */

public static String getTime() {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

   String dateString = formatter.format(currentTime);

   String min;

   min = dateString.substring(14, 16);

   return min;

}

/**

   * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。

   *

   * @param sformat

   *             yyyyMMddhhmmss

   * @return

   */

public static String getUserDate(String sformat) {

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(sformat);

   String dateString = formatter.format(currentTime);

   return dateString;

}

——————————————————————————————————————————–

做成方法

import java.util.*;import java.text.*;import java.util.Calendar;

public class VeDate {

 /**

  * 获取现在时间

  *

  * @return 返回时间类型 yyyy-MM-dd HH:mm:ss

  */

 public static Date getNowDate() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String dateString = formatter.format(currentTime);

  ParsePosition pos = new ParsePosition(8);

  Date currentTime_2 = formatter.parse(dateString, pos);

  return currentTime_2;

 }

 

 /**

  * 获取现在时间

  *

  * @return返回短时间格式 yyyy-MM-dd

  */

 public static Date getNowDateShort() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  String dateString = formatter.format(currentTime);

  ParsePosition pos = new ParsePosition(8);

  Date currentTime_2 = formatter.parse(dateString, pos);

  return currentTime_2;

 }

 

 /**

  * 获取现在时间

  *

  * @return返回字符串格式 yyyy-MM-dd HH:mm:ss

  */

 public static String getStringDate() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String dateString = formatter.format(currentTime);

  return dateString;

 }

 

 /**

  * 获取现在时间

  *

  * @return 返回短时间字符串格式yyyy-MM-dd

  */

 public static String getStringDateShort() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  String dateString = formatter.format(currentTime);

  return dateString;

 }

 

 /**

  * 获取时间 小时:分;秒 HH:mm:ss

  *

  * @return

  */

 public static String getTimeShort() {

  SimpleDateFormat formatter = new SimpleDateFormat(“HH:mm:ss”);

  Date currentTime = new Date();

  String dateString = formatter.format(currentTime);

  return dateString;

 }

 

 /**

  * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss

  *

  * @param strDate

  * @return

  */

 public static Date strToDateLong(String strDate) {

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  ParsePosition pos = new ParsePosition(0);

  Date strtodate = formatter.parse(strDate, pos);

  return strtodate;

 }

 

 /**

  * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss

  *

  * @param dateDate

  * @return

  */

 public static String dateToStrLong(java.util.Date dateDate) {

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String dateString = formatter.format(dateDate);

  return dateString;

 }

 

 /**

  * 将短时间格式时间转换为字符串 yyyy-MM-dd

  *

  * @param dateDate

  * @param k

  * @return

  */

 public static String dateToStr(java.util.Date dateDate) {

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  String dateString = formatter.format(dateDate);

  return dateString;

 }

 

 /**

  * 将短时间格式字符串转换为时间 yyyy-MM-dd

  *

  * @param strDate

  * @return

  */

 public static Date strToDate(String strDate) {

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  ParsePosition pos = new ParsePosition(0);

  Date strtodate = formatter.parse(strDate, pos);

  return strtodate;

 }

 

 /**

  * 得到现在时间

  *

  * @return

  */

 public static Date getNow() {

  Date currentTime = new Date();

  return currentTime;

 }

 

 /**

  * 提取一个月中的最后一天

  *

  * @param day

  * @return

  */

 public static Date getLastDate(long day) {

  Date date = new Date();

  long date_3_hm = date.getTime() – 3600000 * 34 * day;

  Date date_3_hm_date = new Date(date_3_hm);

  return date_3_hm_date;

 }

 

 /**

  * 得到现在时间

  *

  * @return 字符串 yyyyMMdd HHmmss

  */

 public static String getStringToday() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyyMMdd HHmmss”);

  String dateString = formatter.format(currentTime);

  return dateString;

 }

 

 /**

  * 得到现在小时

  */

 public static String getHour() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String dateString = formatter.format(currentTime);

  String hour;

  hour = dateString.substring(11, 13);

  return hour;

 }

 

 /**

  * 得到现在分钟

  *

  * @return

  */

 public static String getTime() {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String dateString = formatter.format(currentTime);

  String min;

  min = dateString.substring(14, 16);

  return min;

 }

 

 /**

  * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。

  *

  * @param sformat

  *            yyyyMMddhhmmss

  * @return

  */

 public static String getUserDate(String sformat) {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(sformat);

  String dateString = formatter.format(currentTime);

  return dateString;

 }

 

 /**

  * 二个小时时间间的差值,必须保证二个时间都是”HH:MM”的格式,返回字符型的分钟

  */

 public static String getTwoHour(String st1, String st2) {

  String[] kk = null;

  String[] jj = null;

  kk = st1.split(“:”);

  jj = st2.split(“:”);

  if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))

   return “0”;

  else {

   double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;

   double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;

   if ((y – u) > 0)

    return y – u + “”;

   else

    return “0”;

  }

 }

 

 /**

  * 得到二个日期间的间隔天数

  */

 public static String getTwoDay(String sj1, String sj2) {

  SimpleDateFormat myFormatter = new SimpleDateFormat(“yyyy-MM-dd”);

  long day = 0;

  try {

   java.util.Date date = myFormatter.parse(sj1);

   java.util.Date mydate = myFormatter.parse(sj2);

   day = (date.getTime() – mydate.getTime()) / (24 * 60 * 60 * 1000);

  } catch (Exception e) {

   return “”;

  }

  return day + “”;

 }

 

 /**

  * 时间前推或后推分钟,其中JJ表示分钟.

  */

 public static String getPreTime(String sj1, String jj) {

  SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

  String mydate1 = “”;

  try {

   Date date1 = format.parse(sj1);

   long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;

   date1.setTime(Time * 1000);

   mydate1 = format.format(date1);

  } catch (Exception e) {

  }

  return mydate1;

 }

 

 /**

  * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数

  */

 public static String getNextDay(String nowdate, String delay) {

  try{

  SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);

  String mdate = “”;

  Date d = strToDate(nowdate);

  long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;

  d.setTime(myTime * 1000);

  mdate = format.format(d);

  return mdate;

  }catch(Exception e){

   return “”;

  }

 }

 

 /**

  * 判断是否润年

  *

  * @param ddate

  * @return

  */

 public static boolean isLeapYear(String ddate) {

 

  /**

   * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年

   * 3.能被4整除同时能被100整除则不是闰年

   */

  Date d = strToDate(ddate);

  GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();

  gc.setTime(d);

  int year = gc.get(Calendar.YEAR);

  if ((year % 400) == 0)

   return true;

  else if ((year % 4) == 0) {

   if ((year % 100) == 0)

    return false;

   else

    return true;

  } else

   return false;

 }

 

 /**

  * 返回美国时间格式 26 Apr 2006

  *

  * @param str

  * @return

  */

 public static String getEDate(String str) {

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  ParsePosition pos = new ParsePosition(0);

  Date strtodate = formatter.parse(str, pos);

  String j = strtodate.toString();

  String[] k = j.split(” “);

  return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);

 }

 

 /**

  * 获取一个月的最后一天

  *

  * @param dat

  * @return

  */

 public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd

  String str = dat.substring(0, 8);

  String month = dat.substring(5, 7);

  int mon = Integer.parseInt(month);

  if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {

   str += “31”;

  } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {

   str += “30”;

  } else {

   if (isLeapYear(dat)) {

    str += “29”;

   } else {

    str += “28”;

   }

  }

  return str;

 }

 

 /**

  * 判断二个时间是否在同一个周

  *

  * @param date1

  * @param date2

  * @return

  */

 public static boolean isSameWeekDates(Date date1, Date date2) {

  Calendar cal1 = Calendar.getInstance();

  Calendar cal2 = Calendar.getInstance();

  cal1.setTime(date1);

  cal2.setTime(date2);

  int subYear = cal1.get(Calendar.YEAR) – cal2.get(Calendar.YEAR);

  if (0 == subYear) {

   if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))

    return true;

  } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {

   // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周

   if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))

    return true;

  } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {

   if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))

    return true;

  }

  return false;

 }

 

 /**

  * 产生周序列,即得到当前时间所在的年度是第几周

  *

  * @return

  */

 public static String getSeqWeek() {

  Calendar c = Calendar.getInstance(Locale.CHINA);

  String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));

  if (week.length() == 1)

   week = “0” + week;

  String year = Integer.toString(c.get(Calendar.YEAR));

  return year + week;

 }

 

 /**

  * 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号

  *

  * @param sdate

  * @param num

  * @return

  */

 public static String getWeek(String sdate, String num) {

  // 再转换为时间

  Date dd = VeDate.strToDate(sdate);

  Calendar c = Calendar.getInstance();

  c.setTime(dd);

  if (num.equals(“1”)) // 返回星期一所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

  else if (num.equals(“2”)) // 返回星期二所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);

  else if (num.equals(“3”)) // 返回星期三所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);

  else if (num.equals(“4”)) // 返回星期四所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);

  else if (num.equals(“5”)) // 返回星期五所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

  else if (num.equals(“6”)) // 返回星期六所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);

  else if (num.equals(“0”)) // 返回星期日所在的日期

   c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

  return new SimpleDateFormat(“yyyy-MM-dd”).format(c.getTime());

 }

 

 /**

  * 根据一个日期,返回是星期几的字符串

  *

  * @param sdate

  * @return

  */

 public static String getWeek(String sdate) {

  // 再转换为时间

  Date date = VeDate.strToDate(sdate);

  Calendar c = Calendar.getInstance();

  c.setTime(date);

  // int hour=c.get(Calendar.DAY_OF_WEEK);

  // hour中存的就是星期几了,其范围 1~7

  // 1=星期日 7=星期六,其他类推

  return new SimpleDateFormat(“EEEE”).format(c.getTime());

 }

 public static String getWeekStr(String sdate){

  String str = “”;

  str = VeDate.getWeek(sdate);

  if(“1”.equals(str)){

   str = “星期日”;

  }else if(“2”.equals(str)){

   str = “星期一”;

  }else if(“3”.equals(str)){

   str = “星期二”;

  }else if(“4”.equals(str)){

   str = “星期三”;

  }else if(“5”.equals(str)){

   str = “星期四”;

  }else if(“6”.equals(str)){

   str = “星期五”;

  }else if(“7”.equals(str)){

   str = “星期六”;

  }

  return str;

 }

 

 /**

  * 两个时间之间的天数

  *

  * @param date1

  * @param date2

  * @return

  */

 public static long getDays(String date1, String date2) {

  if (date1 == null || date1.equals(“”))

   return 0;

  if (date2 == null || date2.equals(“”))

   return 0;

  // 转换为标准时间

  SimpleDateFormat myFormatter = new SimpleDateFormat(“yyyy-MM-dd”);

  java.util.Date date = null;

  java.util.Date mydate = null;

  try {

   date = myFormatter.parse(date1);

   mydate = myFormatter.parse(date2);

  } catch (Exception e) {

  }

  long day = (date.getTime() – mydate.getTime()) / (24 * 60 * 60 * 1000);

  return day;

 }

 

 /**

  * 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间

  * 此函数返回该日历第一行星期日所在的日期

  *

  * @param sdate

  * @return

  */

 public static String getNowMonth(String sdate) {

  // 取该时间所在月的一号

  sdate = sdate.substring(0, 8) + “01”;

 

  // 得到这个月的1号是星期几

  Date date = VeDate.strToDate(sdate);

  Calendar c = Calendar.getInstance();

  c.setTime(date);

  int u = c.get(Calendar.DAY_OF_WEEK);

  String newday = VeDate.getNextDay(sdate, (1 – u) + “”);

  return newday;

 }

 

 /**

  * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数

  *

  * @param k

  *            表示是取几位随机数,可以自己定

  */

 

 public static String getNo(int k) {

 

  return getUserDate(“yyyyMMddhhmmss”) + getRandom(k);

 }

 

 /**

  * 返回一个随机数

  *

  * @param i

  * @return

  */

 public static String getRandom(int i) {

  Random jjj = new Random();

  // int suiJiShu = jjj.nextInt(9);

  if (i == 0)

   return “”;

  String jj = “”;

  for (int k = 0; k < i; k++) {

   jj = jj + jjj.nextInt(9);

  }

  return jj;

 }

 

 /**

  *

  * @param args

  */

 public static boolean RightDate(String date) {

 

  SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);

  ;

  if (date == null)

   return false;

  if (date.length() > 10) {

   sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);

  } else {

   sdf = new SimpleDateFormat(“yyyy-MM-dd”);

  }

  try {

   sdf.parse(date);

  } catch (ParseException pe) {

   return false;

  }

  return true;

 }

 

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

  * //nd=1表示返回的值中包含年度 //yf=1表示返回的值中包含月份 //rq=1表示返回的值中包含日期 //format表示返回的格式 1

  * 以年月日中文返回 2 以横线-返回 // 3 以斜线/返回 4 以缩写不带其它符号形式返回 // 5 以点号.返回

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

 public static String getStringDateMonth(String sdate, String nd, String yf, String rq, String format) {

  Date currentTime = new Date();

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  String dateString = formatter.format(currentTime);

  String s_nd = dateString.substring(0, 4); // 年份

  String s_yf = dateString.substring(5, 7); // 月份

  String s_rq = dateString.substring(8, 10); // 日期

  String sreturn = “”;

  roc.util.MyChar mc = new roc.util.MyChar();

  if (sdate == null || sdate.equals(“”) || !mc.Isdate(sdate)) { // 处理空值情况

   if (nd.equals(“1”)) {

    sreturn = s_nd;

    // 处理间隔符

    if (format.equals(“1”))

     sreturn = sreturn + “年”;

    else if (format.equals(“2”))

     sreturn = sreturn + “-“;

    else if (format.equals(“3”))

     sreturn = sreturn + “/”;

    else if (format.equals(“5”))

     sreturn = sreturn + “.”;

   }

   // 处理月份

   if (yf.equals(“1”)) {

    sreturn = sreturn + s_yf;

    if (format.equals(“1”))

     sreturn = sreturn + “月”;

    else if (format.equals(“2”))

     sreturn = sreturn + “-“;

    else if (format.equals(“3”))

     sreturn = sreturn + “/”;

    else if (format.equals(“5”))

     sreturn = sreturn + “.”;

   }

   // 处理日期

   if (rq.equals(“1”)) {

    sreturn = sreturn + s_rq;

    if (format.equals(“1”))

     sreturn = sreturn + “日”;

   }

  } else {

   // 不是空值,也是一个合法的日期值,则先将其转换为标准的时间格式

   sdate = roc.util.RocDate.getOKDate(sdate);

   s_nd = sdate.substring(0, 4); // 年份

   s_yf = sdate.substring(5, 7); // 月份

   s_rq = sdate.substring(8, 10); // 日期

   if (nd.equals(“1”)) {

    sreturn = s_nd;

    // 处理间隔符

    if (format.equals(“1”))

     sreturn = sreturn + “年”;

    else if (format.equals(“2”))

     sreturn = sreturn + “-“;

    else if (format.equals(“3”))

     sreturn = sreturn + “/”;

    else if (format.equals(“5”))

     sreturn = sreturn + “.”;

   }

   // 处理月份

   if (yf.equals(“1”)) {

    sreturn = sreturn + s_yf;

    if (format.equals(“1”))

     sreturn = sreturn + “月”;

    else if (format.equals(“2”))

     sreturn = sreturn + “-“;

    else if (format.equals(“3”))

     sreturn = sreturn + “/”;

    else if (format.equals(“5”))

     sreturn = sreturn + “.”;

   }

   // 处理日期

   if (rq.equals(“1”)) {

    sreturn = sreturn + s_rq;

    if (format.equals(“1”))

     sreturn = sreturn + “日”;

   }

  }

  return sreturn;

 }

 

 public static String getNextMonthDay(String sdate, int m) {

  sdate = getOKDate(sdate);

  int year = Integer.parseInt(sdate.substring(0, 4));

  int month = Integer.parseInt(sdate.substring(5, 7));

  month = month + m;

  if (month < 0) {

   month = month + 12;

   year = year – 1;

  } else if (month > 12) {

   month = month – 12;

   year = year + 1;

  }

  String smonth = “”;

  if (month < 10)

   smonth = “0” + month;

  else

   smonth = “” + month;

  return year + “-” + smonth + “-10”;

 }

 

 public static String getOKDate(String sdate) {

  if (sdate == null || sdate.equals(“”))

   return getStringDateShort();

 

  if (!VeStr.Isdate(sdate)) {

   sdate = getStringDateShort();

  }

  // 将“/”转换为“-”

  sdate = VeStr.Replace(sdate, “/”, “-“);

  // 如果只有8位长度,则要进行转换

  if (sdate.length() == 8)

   sdate = sdate.substring(0, 4) + “-” + sdate.substring(4, 6) + “-” + sdate.substring(6, 8);

  SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);

  ParsePosition pos = new ParsePosition(0);

  Date strtodate = formatter.parse(sdate, pos);

  String dateString = formatter.format(strtodate);

  return dateString;

 }

 

 public static void main(String[] args) throws Exception {

  try {

   //System.out.print(Integer.valueOf(getTwoDay(“2006-11-03 12:22:10”, “2006-11-02 11:22:09”)));

  } catch (Exception e) {

   throw new Exception();

  }

  //System.out.println(“sss”);

 }

SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”); 
        
        //获取前月的第一天
        Calendar   cal_1=Calendar.getInstance();//获取当前日期 
        cal_1.add(Calendar.MONTH, -1);
        cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        firstDay = format.format(cal_1.getTime());
        System.out.println(“—–1——firstDay:”+firstDay);
        //获取前月的最后一天
        Calendar cale = Calendar.getInstance();   
        cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天 
        lastDay = format.format(cale.getTime());
        System.out.println(“—–2——lastDay:”+lastDay);
        
        
        //获取当前月第一天:
        Calendar c = Calendar.getInstance();    
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        String first = format.format(c.getTime());
        System.out.println(“===============first:”+first);
        
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();    
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));  
        String last = format.format(ca.getTime());
        System.out.println(“===============last:”+last);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package common.alipay.util;

 

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Random;

 

/* *

 *类名:UtilDate

 *功能:自定义订单类

 *详细:工具类,可以用作获取系统日期、订单编号等

 *版本:3.3

 *日期:2012-08-17

 *说明:

 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。

 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。

 */

public class UtilDate {

 

    /** 年月日时分秒(无下划线) yyyyMMddHHmmss */

    public static final String dtLong                  = “yyyyMMddHHmmss”;

    

    /** 完整时间 yyyy-MM-dd HH:mm:ss */

    public static final String simple                  = “yyyy-MM-dd HH:mm:ss”;

    

    /** 年月日(无下划线) yyyyMMdd */

    public static final String dtInteger                 = “yyyyMMdd”;

 

    

    /**

     * 返回系统当前时间(精确到毫秒),作为一个唯一的订单编号

     * @return

     *      以yyyyMMddHHmmss为格式的当前系统时间

     */

public  static String getOrderNum(){

Date date=new Date();

DateFormat df=new SimpleDateFormat(dtLong);

return df.format(date);

}

 

/**

 * 获取系统当前日期(精确到毫秒),格式:yyyy-MM-dd HH:mm:ss

 * @return

 */

public  static String getDateFormatter(){

Date date=new Date();

DateFormat df=new SimpleDateFormat(simple);

return df.format(date);

}

 

/**

 * 获取系统当期年月日(精确到天),格式:yyyyMMdd

 * @return

 */

public static String getDate(){

Date date=new Date();

DateFormat df=new SimpleDateFormat(dtInteger);

return df.format(date);

}

 

/**

 * 产生随机的三位数

 * @return

 */

public static String getThree(){

Random rad=new Random();

return rad.nextInt(1000)+””;

}

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package common.util;

 

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Random;

import java.util.Set;

 

public class CommonUtil {

 

/**

 * 判断字符是否为空

 */

public static boolean isEmpty(String input)

{

if (input == null)

{

return true;

}

else

{

return “”.equals(input);

}

}

 

/**

 * 判断Intger是否为空

 */

public static boolean isEmpty(Integer input )

{

return input == null || input == 0;

}

 

/**

 * 判断集合是否为空

 */

public static boolean isEmpty(Collection<?> input)

{

if (input == null || input.size() == 0)

{

return true;

}

else

{

return input.isEmpty();

}

}

 

/**

 * 判断字符是否非空

 *

 * @param list

 * @return

 */

public static boolean isNotEmpty(String input)

{

return !isEmpty(input);

}

 

/**

 * 判断Integer是否为空和是否为0

 *

 * @param inte

 * @return

 */

public static boolean isNotEmpty(String … input )

{

if(input == null || input.length == 0){

return false;

}

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

{

if(isEmpty(input[i]))

{

return false;

}

}

return true;

}

 

/**

 * 判断集是否非空

 *

 * @param list

 * @return

 */

public static boolean isNotEmpty(Collection<?> input)

{

return !isEmpty(input);

}

 

/**

 * 判断Integer是否为空和是否为0

 *

 * @param inte

 * @return

 */

public static boolean isNotEmpty(Integer input)

{

return input != null && input > 0;

}

 

/**

 * 判断Integer是否为空和是否为0

 *

 * @param inte

 * @return

 */

public static boolean isNotEmpty(Integer … input )

{

if(input == null || input.length == 0){

return false;

}

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

{

if(isEmpty(input[i]))

{

return false;

}

}

return true;

}

 

/**

 * 转成Integer

 *

 * @param obj

 * @return

 */

public static Integer toInteger(Object obj)

{

if (obj == null)

throw new NullPointerException(“数据不存在”);

Integer i = 0;

try

{

i = Integer.parseInt(obj.toString());

}

catch (Exception ex)

{

ex.printStackTrace();

}

return i;

}

 

/**

 * 数组转list<Long>集合

 *

 * @param array

 * @return

 */

public static List<Long> toLongList(String input, String sp)

{

if (CommonUtil.isNotEmpty(input) && CommonUtil.isNotEmpty(sp))

{

String num[] = input.split(sp);

List<Long> list = new ArrayList<Long>();

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

{

list.add(Long.valueOf(num[i]));

}

return list;

}

return null;

}

 

/**

 * 数组转list<Integer>集合

 *

 * @param array

 * @return

 */

public static List<Integer> toIntegerList(Object[] strs)

{

if (strs != null && strs.length != 0)

{

List<Integer> list = new ArrayList<Integer>(strs.length);

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

{

Integer inte = toInteger(strs[i]);

if (inte != null)

{

list.add(inte);

}

}

return list;

}

return null;

}

 

/**

 * @Description: 字符转list集合

 * @param input

 * @param regex

 * @return

 * @return List<Integer>

 * @author LongDing 2015年6月25日 下午4:38:13

 */

public static List<Integer> toIntegerList(String input, String regex)

{

if (CommonUtil.isNotEmpty(input) && CommonUtil.isNotEmpty(regex))

{

String[] strs = input.split(regex);

List<Integer> list = new ArrayList<Integer>(strs.length);

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

{

if (strs[i].matches(“\\d+”))

{

list.add(Integer.parseInt(strs[i]));

}

}

return list;

}

return null;

}

 

/**

 * @Description: String 转Integer 数组

 * @param input

 * @param regex

 * @return

 * @author LongDing 2015年9月22日 下午3:00:26

 */

public static Integer[] toIntegerArray(String input, String regex)

{

if (CommonUtil.isNotEmpty(input) && CommonUtil.isNotEmpty(regex))

{

String[] array = input.split(regex);

if (array != null)

{

Integer[] intArray = new Integer[array.length];

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

{

intArray[i] = Integer.parseInt(array[i].trim());

}

return intArray;

}

}

return null;

}

 

/**

 * @Description: String 转 List<String>

 * @param input

 * @param regex

 * @return

 * @author LongDing 2015年9月22日 下午3:00:26

 */

public static List<String> toStringList(String input, String regex)

{

if (CommonUtil.isNotEmpty(input) && CommonUtil.isNotEmpty(regex))

{

String[] array = input.split(regex);

if (array != null)

{

List<String> list = new ArrayList<String>(array.length);

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

{

if (CommonUtil.isNotEmpty(array[i]))

{

list.add(array[i].trim());

}

}

return list;

}

}

return null;

}

 

/**

 * @Description: String 转 List<String>

 * @param input

 * @param regex

 * @return

 * @author LongDing 2015年9月22日 下午3:00:26

 */

public static String[] toStringArray(String input, String regex)

{

if (CommonUtil.isNotEmpty(input) && CommonUtil.isNotEmpty(regex))

{

return input.split(regex);

}

return null;

}

 

/**

 * @Description: list转数组

 * @param List

 * @return

 * @author LongDing 2015年9月22日 下午3:01:00

 */

public static String[] listToArray(List<String> List)

{

if (CommonUtil.isNotEmpty(List))

{

String[] array = new String[List.size()];

Iterator<String> iter = List.iterator();

int index = 0;

while (iter.hasNext())

{

array[index++] = iter.next();

}

return array;

}

return null;

}

 

/**

 * 获取获取数字字符串

 *

 * @param length

 *              长度

 * @return

 */

public static String getRandomNumber(Integer length)

{

if (length == null || length <= 0)

{

throw new NullPointerException();

}

StringBuilder sb = new StringBuilder();

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

{

sb.append((int) (Math.random() * 10));

}

return sb.toString();

}

 

/**

 * 序列化对象,完全克隆对象

 *

 * @param obj

 * @return

 */

public static Object serializationObject(Object obj)

{

ByteArrayOutputStream bos = null;

ObjectOutputStream oos = null;

ByteArrayInputStream bis = null;

ObjectInputStream ois = null;

try

{

bos = new ByteArrayOutputStream();

oos = new ObjectOutputStream(bos);

oos.writeObject(obj);

byte[] data = bos.toByteArray();

bis = new ByteArrayInputStream(data);

ois = new ObjectInputStream(bis);

return ois.readObject();

}

catch (IOException e)

{

e.printStackTrace();

}

catch (ClassNotFoundException e)

{

e.printStackTrace();

}

finally

{

if (bos != null)

{

try

{

bos.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

if (oos != null)

{

try

{

oos.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

if (bis != null)

{

try

{

bis.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

if (bis != null)

{

try

{

bis.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

if (ois != null)

{

try

{

ois.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

return null;

}

 

/**

 * 校验验证码

 *

 * @param code

 * @param codeType

 * @return

 */

public static boolean validateCode(String code, String codeType)

{

if (!CommonUtil.isEmpty(code) && !CommonUtil.isEmpty(codeType))

{

String serverCode = “”;

// 页面验证码

// if (ConstantUtil.VALIDATE_CODE.equalsIgnoreCase(codeType))

// {

// 页面验证码

// serverCode = (String) RequestUtil.getRequest()

// .getSession().getAttribute(ConstantUtil.VALIDATE_CODE);

// }

/*

 * else if (ConstantUtil.VALIDATE_CODE_PHONE.equals(codeType)) { //

 * 手机验证码 serverCode = (String) RequestUtil.getRequest()

 * .getSession() .getAttribute(ConstantUtil.VALIDATE_CODE_PHONE); }

 * else if

 * (ConstantUtil.VALIDATE_CODE_MAIL.equalsIgnoreCase(codeType)) { //

 * 邮箱验证码 serverCode = (String) RequestUtil.getRequest()

 * .getSession() .getAttribute(ConstantUtil.VALIDATE_CODE_MAIL); }

 */

if (code.equalsIgnoreCase(serverCode))

{

return true;

}

}

return false;

}

 

/**

 * @Description: MD5加密2次

 * @param input

 */

public static String doubleMD5(String input)

{

return MD5(MD5(input));

}

 

/**

 * @Description: MD5加密1次

 * @param input

 */

public static String MD5(String input)

{

if (input != null && input.length() > 0)

{

try

{

MessageDigest md = MessageDigest.getInstance(“MD5”);

md.update(input.getBytes());

byte b[] = md.digest();

int i;

StringBuffer buf = new StringBuffer(“”);

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

{

i = b[offset];

if (i < 0)

i += 256;

if (i < 16)

buf.append(“0”);

buf.append(Integer.toHexString(i));

}

return buf.toString();

}

catch (NoSuchAlgorithmException e)

{

e.printStackTrace();

}

}

return “”;

}

 

public static StringBuffer mapToStringBuffer(Map<Object, Object> map)

{

StringBuffer sbf = new StringBuffer();

if (map != null && map.size() > 0)

{

Set<Entry<Object, Object>> set = map.entrySet();

Iterator<Entry<Object, Object>> iter = set.iterator();

int index = 0;

while (iter.hasNext())

{

Entry<Object, Object> entry = iter.next();

if (index++ != 0)

{

sbf.append(“&”);

}

else

{

sbf.append(“?”);

}

sbf.append(entry.getKey());

sbf.append(“=”);

if (entry.getValue() instanceof String[])

{

String items[] = (String[]) entry.getValue();

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

{

sbf.append(items[i]);

if (i + 1 < items.length)

{

sbf.append(“,”);

}

}

}

else

{

sbf.append(entry.getValue());

}

}

}

return sbf;

}

 

/**

 * @Description: 验证邮箱格式是否正确

 * @param email

 * @return

 * @author LongDing 2015年11月21日 下午7:14:12

 */

public static boolean validateEmail(String email)

{

if (CommonUtil.isNotEmpty(email))

{

return email.matches(“^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$”);

}

return false;

}

 

/**

 * @Description: 验证手机号码格式是否正确

 * @param email

 * @return

 * @author LongDing 2015年11月21日 下午7:14:12

 */

public static boolean validateMobile(String mobile)

{

if (CommonUtil.isNotEmpty(mobile))

{

return mobile.matches(“^(13|15|18)[0-9]{9}$”);

}

return false;

}

 

public static String mapToString(Map<String, String[]> parameterMap)

{

StringBuffer sbf = new StringBuffer();

if (parameterMap != null && parameterMap.size() > 0)

{

Set<Entry<String, String[]>> set = parameterMap.entrySet();

Iterator<Entry<String, String[]>> iter = set.iterator();

int index = 0;

while (iter.hasNext())

{

Entry<String, String[]> entry = iter.next();

if (index++ != 0)

{

sbf.append(“&”);

}

else

{

sbf.append(“?”);

}

sbf.append(entry.getKey());

sbf.append(“=”);

if (entry.getValue() instanceof String[])

{

String items[] = entry.getValue();

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

{

sbf.append(items[i]);

if (i + 1 < items.length)

{

sbf.append(“,”);

}

}

}

else

{

sbf.append(entry.getValue());

}

}

}

return sbf.toString();

}

 

/**

 * 获取随机值

 *

 * @param min

 * @param max

 * @return

 */

public static int getRadomNum(int min, int max)

{

return min + new Random().nextInt(max – min + 1);

}

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/33650.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信