java 获取月、周几
获取月、日 (如:7.13)
/** * 获取当前时间月日 7.13 * @param date * @return */ public static String getMonthDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); //month从0开始 int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); return month+"."+day; }
获取星期几(如:周三)
/** * 获取周几 * @param date * @return */ public static String getWeek(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int weekday = calendar.get(Calendar.DAY_OF_WEEK); String week = null; if (weekday == 1) { week = "周日"; } else if (weekday == 2) { week = "周一"; } else if (weekday == 3) { week = "周二"; } else if (weekday == 4) { week = "周三"; } else if (weekday == 5) { week = "周四"; } else if (weekday == 6) { week = "周五"; } else if (weekday == 7) { week = "周六"; } return week; }
日期字符串转时间(如:2020-05-20)
/** * 根据日期字符串获取时间 * @param str * @return */ public static Date getDate(String str) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date parse = null; try { parse = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return parse; }
获取日期前某天或后某天
/** * 获取当前时间前面某天或者后面某天,date为今天 * @param amount为-1,表示昨天,amount为1表示明天 * @param date * @return */ public static Date getOtherDay(Date date, int amount) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH,amount); Date time = calendar.getTime(); return time; }