使用日曆Calendar+Java獲取日期,一週,一個月等帶星期
1,獲取本週的時間及星期,效果圖如下:
程式碼:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class DateTest {
private static final int FIRST_DAY = Calendar.MONDAY;
public static void main(String[] args) {
List bb=dates();
for (Object object : bb) {
System.out.println(object);
}
}
private static List dates() {
List aa=new ArrayList<>();
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
calendar.add(Calendar.DATE, -1);
}
for (int i = 0; i < 7; i++) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd EE");
aa.add(dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DATE, 1);
}
return aa;
}
}
2,根據日期獲取日期所在的那一週時間及星期,效果如下:
程式碼:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class dateTest2 {
public static void main(String[] args) throws ParseException {
// 定義輸出日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEE");
String aa="2017-06-17 11:21:18";
Date currentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(aa);
// 比如今天是2012-12-25
List<Date> days = dateToWeek(currentDate);
System.out.println("今天的日期: " + sdf.format(currentDate));
for (Date date : days) {
System.out.println(sdf.format(date));
}
}
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<Date>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
fdate.setTime(fTime + (a * 24 * 3600000));
list.add(a-1, fdate);
}
return list;
}
}
3,根據日期獲取日期所在一個月的時間,效果圖如下:
程式碼如下:
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateTest4 {
public static Date[] getDates(String year, String month) throws ParseException {
int maxDate = 0;
Date first = null;
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
first = sdf.parse(year + month);
cal.setTime(first);
maxDate = cal.getMaximum(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat sdf1= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
SimpleDateFormat sdf2= new SimpleDateFormat("yyyy-MM-dd");
Date[] dates = new Date[maxDate];
for (int i = 1; i <= maxDate; i++) {
dates[i - 1] = new Date(first.getTime());
first.setDate(first.getDate() + 1);
String aa=sdf2.format(sdf1.parse(dates[i - 1].toString()));
System.out.println(aa);
}
return dates;
}
public static void main(String[] args) throws ParseException {
getDates("2017", "07");
}
}