[b]Date与字符串间的转换
Date进行计算
获取每个月的第一天和最后一天等等[/b]
Date进行计算
获取每个月的第一天和最后一天等等[/b]
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import sun.misc.Launcher;
/**
* @author zhengtian
*
* @date 2011-6-17 下午02:39:24
*/
@SuppressWarnings("all")
public class test {
private static final String yyyy_MM = "yyyy-MM";
private static final String yyyy_MM_dd = "yyyy-MM-dd";
public static void main(String[] args) {
String dateStr = "2012-3";
System.out.println(getFirstDayTime(dateStr));
System.out.println(getLastDayTime(dateStr));
}
/**
* 得到每个月第一天
*
* @param dateStr
* @return
*/
public static String getFirstDayTime(String dateStr) {
Date date = convertStrToDate(dateStr, yyyy_MM);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, firstDay);
return convertDateToStr(calendar.getTime(), yyyy_MM_dd);
}
/**
* 得到每个月的最后一天
*
* @param dateStr
* @return
*/
public static String getLastDayTime(String dateStr) {
Date date = convertStrToDate(dateStr, yyyy_MM);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.setTime(date);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
return convertDateToStr(calendar.getTime(), yyyy_MM_dd);
}
/**
* Date转换为字符串
*
* @param date
* @param formatStr
* @return
*/
public static String convertDateToStr(Date date, String formatStr) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
return format.format(date);
}
/**
* 字符串转换为Date
*
* @param dateStr
* @param formatStr
* @return
*/
public static Date convertStrToDate(String dateStr, String formatStr) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
try {
return format.parse(dateStr);
} catch (ParseException e) {
return null;
}
}
}