// 这一天是几号 int day = dateTime.getDayOfMonth(); // 这一天是哪月 int month = dateTime.getMothOfYear(); // 这一天是哪年 int year = dateTime.getYear(); // 判断本月是不是9月 if(dateTime.getDayOfMonth() == DateTimeConstants.SEPTEMBER){ //TODO }
// 获取相对于当前时间的月份,比如获取上个月的时间或者下个月的是时间,方法minusMoths接受一个int的参数,如果这个参数等于0,代表本月,大于0代表已经过去的时间,小于0代表还没有到来的时间 LocalDate lastDayOfMonth = new LocalDate().minusMonths(1).dayOfMonth().withMaximumValue();
2、关于星期的操作
DateTime dateTime = new DateTime(); // 今天是星期几 int week = dateTime.getDayOfWeek(); // 判断今天是不是星期三 if(dateTime.getDayOfWeek() == DateTimeConstants.WEDNESDAY){ // TODO }
DateTime currentDateTime = new DateTime(); DateTime targetDateTime = new DateTime(2017,10,1,0,0,0);
// 相差多少年 int years = Years.yearsBetween(currentDateTime,targetDateTime).getYears(); // 相差多少月 int months = Months.monthsBetween(currentDateTime,targetDateTime).getMonths(); // 距离国庆放假还有多少天,嘎嘎! int days = Days.daysBetween(currentDateTime,targetDateTime).getDays(); // 相差多少小时 int hours = Hours.hoursBetween(currentDateTime,targetDateTime).getHours(); // 相差多少分钟 int minutes = Minutes.minutesBetween(currentDateTime,targetDateTime).getMinutes(); // 相差多少秒 int seconds = Seconds.secondsBetween(currentDateTime,targetDateTime).getSeconds(); // 相差多少周 int weeks = Weeks.weeksBetween(currentDateTime,targetDateTime).getWeeks();
4、获取零点相关的时间
DateTime currentDateTime = new DateTime(); // 今天的零点 DateTime dateTime = currentDateTime.withMillisOfDay(0); // 昨天的零点 DateTime dateTime = currentDateTime.withMillisOfDay(0).plusDays(-1); // 明天的零点 DateTime dateTime = currentDateTime.withMillisOfDay(0).plusDays(1); // 这一年最后一天0点 new DateTime().dayOfYear().withMaximumValue().withMillisOfDay(0) // 这一年第一天0点 new DateTime().dayOfYear().withMinimumValue().withMillisOfDay(0) // 这个月最后一天0点 new DateTime().dayOfMonth().withMaximumValue().withMillisOfDay(0) // 这个月月初0点 new DateTime().dayOfMonth().withMinimumValue().withMillisOfDay(0)
注意:要获取多少天后或者多少天前的零点,只需在plusDays()方法中填写相应参数即可
三、准确使用Joda Time的时间处理类
1、格式化就这么简单
// 格式化时间 DateTime currentDateTime = new DateTime(); currentDateTime.toString("yyyy-MM-dd HH:mm:ss");
// 指定时区格式化 String format = "yyyy-MM-dd HH:mm:ss"; DateTime dateTime = new DateTime(); dateTime.toString(format, Locale.US);
// 格式化时分秒(单位毫秒并且最大可格式23:59:59,超出将报错) int millis = 120000; LocalTime localTime = new LocalTime().withMillisOfDay(millis); localTime.toString("HH:mm:ss");