在JAVA的使用过程中,经常要处理一些时间和日期,如果将其封装的话,可以方便以后使用。下面是我封装的一个简单的时间日期处理类,如果以后要有其他的扩展,下次再补充一下。
代码如下所示:
package cn.ac.iscas.gz.sems.domain.common.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
/**
* 以指定的格式来格式化日期
*
* @param date Date
* @param format String
* @return String
*/
public static String formatDateByFormat(java.util.Date date,String format)
{
String result = "";
if(date != null)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(date);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
return result;
}
/**
* 获取上个月字符串形式(yyyy-MM)
* @param currMonth
* @return
*/
public static String getLastMonth(String currMonth){
Date currDate = null;
String lastMonth = "";
DateFormat df2 = DateFormat.getDateInstance();
try {
currDate = df2.parse(currMonth);
Calendar calendar=Calendar.getInstance();
calendar.setTime(currDate);
calendar.add(Calendar.MONTH, -1);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
lastMonth = sdf.format(calendar.getTime());
} catch (ParseException e) {
lastMonth = "";
}
return lastMonth;
}
/**
* 获取上一天的日期
* 获取上个月字符串形式(yyyy-MM-dd)
* return prevDate
*/
public static String getPrevDate(String currDateStr){
Date currDate = null;
//上一个日期
String prevDate = "";
DateFormat df2 = DateFormat.getDateInstance();
try {
currDate = df2.parse(currDateStr);
Calendar calendar=Calendar.getInstance();
calendar.setTime(currDate);
//减去上一天的日期
calendar.add(Calendar.DATE, -1);
//格式化日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
prevDate = sdf.format(calendar.getTime());
} catch (ParseException e) {
prevDate = "";
}
return prevDate;
}
/**
* 得到当前系统的日期,时间格式为 yyyy-MM-dd
* @currStrDate
*/
public static String getLastDate(){
//得到当前系统日历
java.util.Calendar c=java.util.Calendar.getInstance();
//日期格式:yyyy年MM月dd日hh时mm分ss秒
java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyy-MM-dd");
//格式化该日期,得到字符串值
String currStrDate = f.format(c.getTime());
return currStrDate;
}
// public static void main(String[] args) {
System.out.println(getPrevDate("2012-6-1"));
// getLastDate();
// }
}
*****