package com.xtuone.friday.server.modules.curriculum.fetchData.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class CalendarUtil {
/**
*
*
*
* @param beginDate
* @param endDate
* @param dateFormat
* 格式
* @return 指定时间之间的字符串格式的时间
*/
public static List<String> getDatesBetweenTwoDate(String beginDate, String endDate, String dateFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date dBegin;
Date dEnd;
List<Date> lDate = new ArrayList<Date>();
List<String> list = new ArrayList<String>();
try {
dBegin = sdf.parse(beginDate);
dEnd = sdf.parse(endDate);
lDate.add(dBegin);// 把开始时间加入集合
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(dBegin);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, 1);
// 测试此日期是否在指定日期之后
if (dEnd.after(cal.getTime())) {
lDate.add(cal.getTime());
} else {
break;
}
}
lDate.add(dEnd);// 把结束时间加入集合
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < lDate.size(); i++) {
list.add(sdf.format(lDate.get(i)));
}
return list;
}
/***
*
*
* @Description 根据指定日起或者当前日期返回 星期 不传参的话是当前时间
* @param 2014年4月1日17:14:44
* @return String 星期的字符串 1,2
*/
public static String dateConvensToWeekDay(String time) {
try {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
if ("".equals(time)) {
date = new Date();
} else {
date = formatter.parse(time);
}
Integer[] weeks = { 7, 1, 2, 3, 4, 5, 6 };
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (week_index < 0) {
week_index = 0;
}
return weeks[week_index] + "";
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//根据 当前日期 返回指定天数之后的日期
public static String getDateAfterDay(String dateBegin,int dayPlus){
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
if("".equals(dateBegin)){
date= new Date();
}
else{
date = formatter.parse(dateBegin);
}
// dayPlus表示指定日期和当前日期相差的天数
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + dayPlus);
String newTime=formatter.format(cal.getTime());
return newTime;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
System.out.println(CalendarUtil.getDateAfterDay("2014-04-02", 0));
}
}
Calendar类的常见用法
最新推荐文章于 2021-03-08 16:28:15 发布