关于java中的时间

java中时间的转换:
把Date转换成时间long

date.getTime();
public static void main(String[] args) throws Exception{
String endDate = "12/08/2015";
String sortingDate = "2015-08-12 12:51:17";
String sortingDateDB="2015-08-12 12:55:17";
String endDateDB="2015-08-13 12:51:17";
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long sortingDateLong = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sortingDate)).getTime();
long endDateLong = (new SimpleDateFormat("dd/MM/yy").parse(endDate)).getTime();
long sortingDateDBLong = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sortingDateDB)).getTime();
long endDateDBLong = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateDB)).getTime();
// 比较两个long date相差多少分钟
long diffSortingDate = (Long.valueOf(sortingDateDBLong) - Long.valueOf(sortingDateLong))/nm;
//比较两个long date相差多少天
long diffEndDate = (Long.valueOf(endDateDBLong) - Long.valueOf(endDateLong))/nd;
System.out.println("diffSort:"+diffSortingDate+"  diffEnd:"+diffEndDate);
}

把 12/07/15 2.42pm转换成2015/07/13 14:42:00
and 把 “today 2.42pm" 转换成时间格式2015/07/13 14:42:00

public static String dateFor(String time) {

String timeSplit = time.split(" ")[1];
String todayTime = time.split(" ")[0];
if ("today".equals(todayTime)) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String currentTime = sdf.format(date);
time = currentTime + " " + timeSplit;
}


try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy hh.mmaaa",
Locale.ENGLISH);
Date newDate = format.parse(time);
DateFormat formatTo = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return formatTo.format(newDate);
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

把06:19 am 13/07/15这种格式转换成 2015/07/13 06:19:00

public static String dateCon(String time) {
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm aa dd/MM/yy",
Locale.ENGLISH);
Date newDate = format.parse(time);
DateFormat formatTo = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String timeCon = formatTo.format(newDate);
return timeCon;
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}




猜你喜欢

转载自blog.csdn.net/u012989656/article/details/46862637