我有以下输入
String day = "Tuesday";
SimpleDateFormat dayFormat = new SimpleDateFormat("E");
Date date1 = dayFormat.parse(day);
今天的日期是 2012-10-19。通过输入这一天,我想取回下一个即将到来的日期和时间。如何将星期二转换为字符串,如下所示:2012-10-20 00:00?
谢谢你。
我有以下输入
String day = "Tuesday";
SimpleDateFormat dayFormat = new SimpleDateFormat("E");
Date date1 = dayFormat.parse(day);
今天的日期是 2012-10-19。通过输入这一天,我想取回下一个即将到来的日期和时间。如何将星期二转换为字符串,如下所示:2012-10-20 00:00?
谢谢你。
Use the Calendar
API as follows -
String day = "Tue";
SimpleDateFormat dayFormat = new SimpleDateFormat("EEE");
Date date1 = dayFormat.parse(day);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
//just keep adding a day to current date until the day of week is same
Calendar cal = Calendar.getInstance();
while(cal.get(Calendar.DAY_OF_WEEK) != cal1.get(Calendar.DAY_OF_WEEK)) {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(cal.getTime());
Output:
Tue Oct 23 22:34:25 CDT 2012
Calendar
这是一个关于如何使用课程获得下周一的示例。
Calendar now = Calendar.getInstance();
int weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday != Calendar.MONDAY)
{
// calculate how much to add
// the 2 is the difference between Saturday and Monday
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
// now is the date you want
Date date = now.getTime();
String format = new SimpleDateFormat(...).format(date);
来自: http: //www.coderanch.com/t/385117/java/java/date-next-Monday
更多:http ://www.java2s.com/Code/Java/Data-Type/GetNextMonday.htm
您可以Calendar
用于简单的日期操作。例如:
Calendar calendar = Calendar.getInstance(); //gets a localized Calendar instance
calendar.setTime(date1); //sets the Calendar time to your date
calendar.add(Calendar.DATE, 1); //adds 1 day
Date date2 = calendar.getTime(); //gets the resulting date