![]()
package yunup.com.yaomeanagernew.tool; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by user on 2017/10/11. */ public class MyDateTimeUtils { public static final int DAY = 1; public static final int WEEK = 2; public static final int MOTH = 3; /** * @param type 要返回的类型 (日,周,月) * @param number 返回的数量(例如近4天) * @param fromat 返回的日期的格式(yyyy-MM-dd HH:mm:ss:ms) * @return */ public static String[] getLatelyDate(int type, int number, String fromat) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromat); Calendar calendar = Calendar.getInstance(); long currentTime = calendar.getTimeInMillis(); String[] strings = new String[number]; switch (type) { case DAY: String currentDay = simpleDateFormat.format(calendar.getTimeInMillis());//当前的日期 strings[number - 1] = currentDay; for (int j = 0; j < number - 1; j++) { calendar.add(Calendar.DAY_OF_MONTH, -1);//前一天的日期 strings[number - 1 - j - 1] = simpleDateFormat.format(calendar.getTimeInMillis()); } return strings; case WEEK: int getcurrentWeek = calendar.get(Calendar.WEEK_OF_MONTH);//获取当前是周几 int currentWeek = 1;//这个才是真实的周几 if (getcurrentWeek - 1 == 0) { currentWeek = 7; } else { currentWeek = getcurrentWeek - 1; } String week1 = simpleDateFormat.format(calendar.getTimeInMillis());//当前的日期 strings[number - 1] = week1; calendar.add(Calendar.DAY_OF_MONTH, -currentWeek);//上周 周末 的日期 时间 String week2 = simpleDateFormat.format(calendar.getTimeInMillis());//当前的日期 strings[number - 2] = week2; for (int j = 0; j < number - 2; j++) { calendar.add(Calendar.DAY_OF_MONTH, -7);//出了本周和上周,其他的一律减去7天就是 上周的周末 strings[number - 2 - j - 1] = simpleDateFormat.format(calendar.getTimeInMillis()); } return strings; case MOTH: int currentMonth = calendar.get(Calendar.MONTH);//获取当前月份 int currentYear = calendar.get(Calendar.YEAR);//获取当前年份 // strings[number - 1] = currentYear + "年" + currentMonth + "月"; strings[number - 1] = simpleDateFormat.format(calendar.getTimeInMillis()); for (int j = 0; j < number - 1; j++) { currentMonth--; if (currentMonth == 0) { currentMonth = 12; currentYear--; } calendar.set(currentYear,currentMonth,calendar.get(Calendar.DAY_OF_MONTH)); // strings[number - 1 - j - 1] = currentYear + "年" + currentMonth + "月"; strings[number - 1 - j - 1] = simpleDateFormat.format(calendar.getTimeInMillis()); } return strings; } return null; } }
获取当前时间日期的前n天日期
最新推荐文章于 2026-03-03 00:06:01 发布
这是一个Java工具类,用于获取当前日期之前的指定天数、周数或月数的日期。通过传入类型(日、周、月)、数量和日期格式,可以返回一个字符串数组,包含从当前日期开始往前推算的日期。

872

被折叠的 条评论
为什么被折叠?



