java calendar 下个月_java Calendar获取某个时间上个月的时间

java8的时间api很好用,但有的场景用Calendar也是很合适的

/**

* 从当前时间获取上个月的第一天和最后一天

*/

private void getPreMonthDate(String startDate) throws Exception {

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = getPreMonth(startDate);

//获取某月最小天数

int firstDay = c.getActualMinimum(Calendar.DAY_OF_MONTH);

//设置日历中月份的最小天数

c.set(Calendar.DAY_OF_MONTH, firstDay);

// 上个月第一天

String startTime = format.format(c.getTime());

Calendar c2 = getPreMonth(startDate);

int lastDay = c2.getActualMaximum(Calendar.DAY_OF_MONTH);

c2.set(Calendar.DAY_OF_MONTH, lastDay);

String endTime = format.format(c2.getTime());

}

/**

* 从当前时间"yyyy-MM-dd"格式获取上个月的时间

*/

private Calendar getPreMonth(String startDate) throws Exception{

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = Calendar.getInstance();

Date date = format.parse(startDate);

c.setTime(date);

c.add(Calendar.MONTH, -1);

return c;

}

获取上周的时间也是一个道理

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = Calendar.getInstance();

Date date = format.parse("2020-05-01");

c.setTime(date);

c.add(Calendar.DATE, -7);

format.format(c.getTime());

获取当前星期内星期*的date

LocalDate currentDate = LocalDate.now();

// 获取本周星期*的date

LocalDate mondayLocalDate = currentDate.with(DayOfWeek.MONDAY);

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

mondayLocalDate.format(dateTimeFormatter);

// 获取上周内 「星期*」的 date

LocalDate previousDate = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));

获取当天0点10位时间戳

Long time = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).toEpochSecond(ZoneOffset.of("+8"));

String format = String.format("local:time:%s", time);

根据时间戳和日期格式转化成日期字符串

String date =getDateStringByTimestamp(1234567890, "yyyyMMdd");

public static String getDateStringByTimestamp(Integer timestamp, String format) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

return formatter.format(LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneOffset.of("+8")));

}

获取当月第一天的时间

//获取当月第一天

public static LocalDate getCurMonthFirstDay() {

LocalDate currentDate = LocalDate.now();

return currentDate.with(TemporalAdjusters.firstDayOfMonth());

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值