java 学习随笔《时间篇》

1.获取指定时间的Date

SimpleDateFormat accountDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String accountDateString = "2013-05-01 00:00:00";

Date accountTime = accountDateFormat.parse(accountDateString);

2.Date转换成String

Date date = new Date();
SimpleDateFormat accountDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String accountTime = accountDateFormat .format(date);

3.String转换成DateTime

String testDate = "2013-01-14 16:00:00";
SimpleDateFormat accountDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateTime = null; 
try {
  dateTime = accountDateFormat.parse(testDate); 
} catch (ParseException e) {
  e.printStackTrace();
}

4.Date转换为Timestamp

Date date = new Date();  
Timestamp timestamp = new Timestamp(date.getTime()); 

5.处理时间

Date d = new Date();
DateTime now = new DateTime(d);
DateTime todayBookTime =  new DateTime(now.get(DateTimeFieldType.year()), now.get(DateTimeFieldType.monthOfYear()), now.get(DateTimeFieldType.dayOfMonth()), 16, 0);
DateTime tomorromBookTime = todayBookTime.plusHours(24);
DateTime yesterdayBookTime = todayBookTime.plusHours(-24);

if (now.isAfter(yesterdayBookTime) && now.isBefore(todayBookTime)) {
  bookTime = todayBookTime.toDate();
} else if (now.isAfter(todayBookTime)) {
  bookTime = tomorromBookTime.toDate();
}
原文地址:https://www.cnblogs.com/crab-allm/p/3363718.html