java日期的转化

public static Date toDate(int year, int month, int day) {
Date d = new Date();
d = DateUtils.setYears(d, year);
d = DateUtils.setMonths(d, month - 1);
d = DateUtils.setDays(d, day);
d = DateUtils.setHours(d, 0);
d = DateUtils.setMinutes(d, 0);
d = DateUtils.setSeconds(d, 0);
d = DateUtils.setMilliseconds(d, 0);
return d;
}

public static Date toDate(String dateStr) {
if (StringUtils.isBlank(dateStr)) {
return null;
}
String[] dateStrArray = dateStr.split("-");
int year = Integer.parseInt(dateStrArray[0]);
int month = Integer.parseInt(dateStrArray[1]);
int day = Integer.parseInt(dateStrArray[2]);
return toDate(year, month, day);
}

public static Calendar toCalendar(String fromdate) {
Calendar cld1 = Calendar.getInstance();
try {
int year = Integer.parseInt(fromdate.split("-")[0]);
int month = Integer.parseInt(fromdate.split("-")[1]) - 1;
int date = Integer.parseInt(fromdate.split("-")[2]);
cld1.set(year, month, date, 0, 0, 0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return cld1;
}

public static Calendar toCalendar(String fromdate,int hour,int minter,int second) {
Calendar cld1 = Calendar.getInstance();
try {
int year = Integer.parseInt(fromdate.split("-")[0]);
int month = Integer.parseInt(fromdate.split("-")[1]) - 1;
int date = Integer.parseInt(fromdate.split("-")[2]);
cld1.set(Calendar.YEAR, year);
cld1.set(Calendar.MONTH, month);
cld1.set(Calendar.DAY_OF_MONTH, date);
cld1.set(Calendar.HOUR_OF_DAY, hour);
cld1.set(Calendar.MINUTE, minter);
cld1.set(Calendar.SECOND, second);
cld1.set(Calendar.MILLISECOND, 0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return cld1;
}

public static String formatDate(Date d, String pattern) {
if (d == null || StringUtils.isBlank(pattern)) {
return "";
}
return DateFormatUtils.format(d, pattern);
}

public static String formatDate(Date d) {
if (d == null) {
return "";
}
return DateFormatUtils.format(d, "yyyy-MM-dd");
}
时间差值:
Date dateTime = StringUtil.StringToDate(datetime);
Long longtime = (new Date()).getTime()-dateTime.getTime();
Long sec = longtime/1000;
Long mil =  longtime/(1000*60);
Long h = longtime/(1000*60*60);
Long d = longtime/(1000*60*60*24);
string转化Date
//日期转化
public static  Date StringToDate(String dateStr){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date bdate = null;
try {
bdate = formatter.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();

return bdate;
}

你可能感兴趣的:(Date,String)