首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 惯用日期操作对象

2012-12-26 
java 常用日期操作对象import java.util.Calendarimport java.text.FieldPositionimport java.text.Pars

java 常用日期操作对象

import java.util.Calendar;import java.text.FieldPosition;import java.text.ParsePosition;import java.text.SimpleDateFormat;/** * 对日期的操作,如格式化,向前,向后推算日期 */public class DateUtil {static final SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy年MM月dd日");static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/** * 判断指定日期、日期时间、时间是否比当前日期时间后。 *  * @param theTime 指定日期、日期时间、时间。 * @return 更后返回true,否则返回false。 */public static boolean isAfter(String theTime) {switch (theTime.length()) {case 5:return (get("HH:mm").compareTo(theTime) > 0);case 8:return (get("HH:mm:ss").compareTo(theTime) > 0);case 11:if (theTime.charAt(2) == ' ')return (get("dd HH:mm:ss").compareTo(theTime) > 0);if (theTime.charAt(5) == ' ')return (get("MM-dd HH:mm").compareTo(theTime) > 0);case 14:return (get("MM-dd HH:mm:ss").compareTo(theTime) > 0);case 17:return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) > 0);case 19:return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) > 0);}return false;}/** * 判断指定日期、日期时间、时间是否比当前日期时间前。 *  * @param theTime 指定日期、日期时间、时间。 * @return 更前返回true,否则返回false。 */public static boolean isBefore(String theTime) {switch (theTime.length()) {case 5:return (get("HH:mm").compareTo(theTime) < 0);case 8:return (get("HH:mm:ss").compareTo(theTime) < 0);case 11:if (theTime.charAt(2) == ' ')return (get("dd HH:mm:ss").compareTo(theTime) < 0);if (theTime.charAt(5) == ' ')return (get("MM-dd HH:mm").compareTo(theTime) < 0);case 14:return (get("MM-dd HH:mm:ss").compareTo(theTime) < 0);case 17:return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) < 0);case 19:return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) >= 0);}return false;}/** *  按照数据库日期预定的格式取得当前的日期字符串。 *  * * @return “yyyy-MM-dd”格式的当前时间字符串。 */public static String getDate() {return sdf2.format(new java.util.Date());}/** * 获取当时指定毫秒数后的日期对象。 *  * @param seconds 指定毫秒数。 * @return 当时指定毫秒数后的日期对象。 */public static java.util.Date getDate(long seconds) {return new java.util.Date(new java.util.Date().getTime() + seconds* 1000);}/** *  按照数据库日期预定的格式取得当前的日期字符串。 *  * * @return “yyyy-MM-dd”格式的当前时间字符串。 */public static String getDate(Calendar ca) {return sdf2.format(ca.getTime());}/** *  按照数据库日期预定的格式取得当前的日期字符串。 *  * * @return “yyyy-MM-dd”格式的当前时间字符串。 */public static String getDate(java.util.Date date) {return sdf2.format(date);}/** * 按照指定的日期/时间格式返回日期/时间字符串。 *  * @param dateFormatString  格式字符串。 * @return 格式化后的日期字符串。 */public static String get(String dateFormatString) {try {return new java.text.SimpleDateFormat(dateFormatString).format(new java.util.Date());} catch (Exception e) {}return null;}/** * 按照给定的 日期/时间 格式 生成 以java.util.Date对象给出的日期/时间 的字符串。 *  * @param date 指定的日期对象。 * @param dateFormatString 格式字符串。 * @return 格式化后的日期字符串。 */public static String get(java.util.Date date, String dateFormatString) {try {return new java.text.SimpleDateFormat(dateFormatString).format(date);} catch (Exception e) {}return null;}/** * 按照给定的 日期/时间 格式 生成 以java.util.Calendar对象给出的日期/时间 的字符串。 *  * @param calendar 指定的日历对象。 * @param dateFormatString 格式字符串。 * @return 格式化后的日期字符串。 */public static String get(java.util.Calendar calendar, String dateFormatString) {try {return new java.text.SimpleDateFormat(dateFormatString).format(calendar.getTime());} catch (Exception e) {}return null;}/** * 自动分析多种格式的日期、日期时间、时间字符串对象解析为Calendar对象,最小级别是秒级。 * 目前支持格式: * yyyy-MM-dd HH:mm:ss * MM-dd HH:mm:ss 默认为当年 * dd HH:mm:ss 默认为当年当月 * dd HH:mm 默认为当年当月 零秒 * MM-dd HH:mm 默认为当年 零秒 * yyyy-MM-dd 默认为零时零分零秒 * MM-dd 默认为当年 零时零分零秒 * HH:mm:ss 默认为当年当月当日 * HH:mm 默认为当年当月当日 零秒 *  * yyyy/MM/dd HH:mm:ss * yy/MM/dd HH:mm:ss * MM/dd HH:mm:ss * dd HH:mm:ss *  * yyyy年MM月dd日HH点mm分ss秒 * yy年MM月dd日HH点mm分ss秒 * MM月dd日HH点mm分ss秒 * dd日HH点mm分ss秒 * HH点mm分ss秒 * HH点mm分 * @param datetime 日期、日期时间、时间字符串。 * @return 解析成功返回日历对象,失败返回null。 */public static Calendar parse(String datetime) {if(datetime!=null){//当不是标准格式时,则进行格式化if (datetime.length()!=19) {datetime=formatToEnglish(datetime);}try {//创建一个日历对象Calendar rightNow = Calendar.getInstance();//设置日历翻到指定日期时间rightNow.setTime(sdf1.parse(datetime));//返回设置好的日期return rightNow;} catch (Exception e) {}}return null;}/** * 用指定的日期对象得到日期时间的字符串形式。 *  * @param date java.util.Date对象。 * @return 日期时间的字符串形式。 */public static String getDateTime(java.util.Date date) {return sdf1.format(date);}/** * 用给定的日期得到指定延迟秒数的日期时间字符串。 *  * @param date java.util.Date对象。 * @param seconds 秒数。 * @return 延迟后的日期时间。 */public static String getDateTime(java.util.Date date, int seconds) {return sdf1.format(new java.util.Date(date.getTime() + seconds * 1000));}/** * 获得今日与指定日历之间的天数。 *  * @param last 指定的日历。 * @return 当日与指定日历之间的天数。 */public static int getDays(Calendar last) {Calendar right = Calendar.getInstance();long theTime = right.getTimeInMillis() - last.getTimeInMillis();return (int) (theTime / (3600000 * 24));}private static int seed = 0;/** * 获取毫秒级的指定长度的字符串。 * @param length 指定的字符串长度。 * @return 毫秒级的指定长度的字符串。 */public static String getRandomString(int length) {seed++;Calendar right = Calendar.getInstance();String tmp = Long.toString(right.getTimeInMillis() * seed + seed);length = tmp.length() - length;return (length < 0) ? tmp : tmp.substring(length);}/** * 用指定格式的日期时间来的得到日期时间对象。 *  * @param dateFormatString 日期时间格式字符串。 * @return 返回java.util.Date类型日期时间对象。 */public static java.util.Date getToday(String dateFormatString) {try {return parse(new java.text.SimpleDateFormat(dateFormatString).format(Calendar.getInstance().getTime())).getTime();} catch (Exception e) {}return null;}/** * 得到指定格式的当日的后一天的日期时间对象。 *  * @param dateFormatString 日期时间格式字符串。 * @return 返回java.util.Date类型日期时间对象。 */public static java.util.Date getTomorrow(String dateFormatString) {try {return parse(new java.text.SimpleDateFormat(dateFormatString).format(new java.util.Date(new java.util.Date().getTime() + 24 * 3600 * 1000))).getTime();} catch (Exception e) {}return null;}/** * 返回今天之前或之后若干天的日期字符串。 * @param days 指定的天数,“days<0”表示前days天;“days>0”表示后days天,“days=0”表示当天。 * @return 返回格式为“yyyy-MM-dd”的日期。 */public static String getDate(int days) {Calendar now = Calendar.getInstance();now.add(Calendar.DAY_OF_MONTH, days);return sdf2.format(now.getTime());}/** * 得到指定date日期之前或之后若干天的日期字符串。 * @param date 指定的日期字符串。 * @param days 指定的天数,“days<0”表示前days天;“days>0”表示后days天,“days=0”表示当天。 * @return 字符串形式的日期。 */public static String getDate(String date,int days){java.util.Date dateTemp = sdf2.parse(date, new ParsePosition(0));Calendar calendar = Calendar.getInstance();calendar.setTime(dateTemp);// 要加减的日期calendar.add(Calendar.DATE, days);java.util.Date nowTime = calendar.getTime();StringBuffer buffer = sdf2.format(nowTime, new StringBuffer(""),new FieldPosition(0));return new String(buffer);}/** * 格式化以:“年”、“月”、“日”、“时”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ” * 分割日期时间的日期时间字符串。统一格式化成英文的日期时间,例:2009-11-09 13:32:56。 */public static String formatToEnglish(String datetime){String date=sdf2.format(Calendar.getInstance().getTime());String yy=date.substring(0,2);String year=date.substring(0,4);String month=date.substring(5,7);String day=date.substring(8,10);String datetimeBak=datetime.replace("日", " ");datetimeBak=datetimeBak.replace(" ", " ");datetimeBak=datetimeBak.replaceAll(" +", " ");//把日期和时间切割成两部分String dt[]=datetimeBak.split(" ");String format=null;String temp[]=getArray(datetime);if(temp!=null&&dt!=null){switch (temp.length){case 1://只有日if(temp[0].length()==1){temp[0]="0"+temp[0];}format=year+"-"+month+"-"+temp[1]+" 00:00:00";break;case 2:for (int i = 0; i < temp.length; i++) {if(temp[i].length()==1){temp[i]="0"+temp[i];}}//判断为日期或是时间if(dt.length==1){//判断为时间:由时、分、秒组成if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("点")){format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":00";}//判断为日期:由月、日组成else{format=year+"-"+temp[0]+"-"+temp[1]+" 00:00:00";}}//判断为日期时间:由日、时组成else if(dt.length==2){format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":00:00";}break;case 3://判断为日期或是时间if(dt.length==1){//判断为时间:由时、分、秒组成if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("点")){for (int i = 0; i < temp.length; i++) {if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":"+temp[2];}//判断为日期:由年、月、日组成else{for (int i = 0; i < temp.length; i++) {if(temp[0].length()!=4){temp[0]=yy+temp[0];}else if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=temp[0]+"-"+temp[1]+"-"+temp[2]+" 00:00:00";}}//判断为日期时间:由日、时组成else if(dt.length==2){for (int i = 0; i < temp.length; i++) {if(temp[i].length()==1){temp[i]="0"+temp[i];}}String dateArray[]=getArray(dt[0]);String timeArray[]=getArray(dt[1]);//判断为月、日、时组成if(dateArray.length==2 && timeArray.length==1){format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":00:00";}//判断为日、时、分组成else if(dateArray.length==1 && timeArray.length==2){format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":00";}}break;case 4://判断为日期时间if(dt.length==2){String dateArray[]=getArray(dt[0]);String timeArray[]=getArray(dt[1]);//判断为年、月、日、时组成if(dateArray.length==3 && timeArray.length==1){for (int i = 0; i < temp.length; i++) {if(temp[0].length()!=4){temp[0]=yy+temp[0];}else if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+"00:00";}else{for (int i = 0; i < temp.length; i++) {if(temp[i].length()==1){temp[i]="0"+temp[i];}}//判断为日、时、分、秒组成if(dateArray.length==1 && timeArray.length==3){format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":"+temp[3];}//判断为月、日、时、分组成else if(dateArray.length==2 && timeArray.length==2){format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":00";}}}break;case 5:if(dt.length==2){String dateArray[]=getArray(dt[0]);String timeArray[]=getArray(dt[1]);//判断为月、日、时、分、秒组成if(dateArray.length==2 && timeArray.length==3){for (int i = 0; i < temp.length; i++) {if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":"+temp[4];}//判断为年、月、日、时、分组成else if(dateArray.length==3 && timeArray.length==2){for (int i = 0; i < temp.length; i++) {if(temp[0].length()!=4){temp[0]=yy+temp[0];}else if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":00";}}break;case 6:for (int i = 0; i < temp.length; i++) {if(temp[0].length()!=4){temp[0]=yy+temp[0];}else if(temp[i].length()==1){temp[i]="0"+temp[i];}}format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":"+temp[5];break;}}return format;}/** * 把多种中文中易出现格式的日期时间中各项转换成数组。 */private static String[] getArray(String datetime){String array[]=null;if(datetime!=null){//把半角空格替换掉datetime=datetime.replace(" ", "-");//把全角空格替换掉datetime=datetime.replace(" ", "-");datetime=datetime.replace("年", "-");datetime=datetime.replace("月", "-");datetime=datetime.replace("日", "-");datetime=datetime.replace("点", "-");datetime=datetime.replace("分", "-");datetime=datetime.replace("秒", "");datetime=datetime.replace(",", "-");datetime=datetime.replace(",", "-");datetime=datetime.replace(".", "-");datetime=datetime.replace(":", "-");datetime=datetime.replace(":", "-");datetime=datetime.replace("-", "-");datetime=datetime.replace("/", "-");//多个“-”替换成一个“-”datetime=datetime.replaceAll("-+", "-");//把日期时间分割成每个项array=datetime.split("-");}return array;}/** * 格式化以:“年”、“月”、“日”、“时”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ” * 分割日期时间的日期时间字符串。统一格式化成中文的日期时间,例:2009年11月09日13时32分56秒。 */public static String formatToChinese(String datetime){datetime=formatToEnglish(datetime);if(datetime==null||datetime.equals("")){return null;}String str[]=datetime.split(":|-| ");return str[0]+"年"+str[1]+"月"+str[2]+"日 "+str[3]+"点"+str[4]+"分"+str[5]+"秒";}

?

热点排行