我有以下输入
String day = "Tuesday";
SimpleDateFormat dayFormat = new SimpleDateFormat("E");
Date date1 = dayFormat.parse(day);
今天的日期是2012-10-19。进入这一天,我想回到下一个即将到来的日期和时间。 如何将星期二转换为字符串如下:2012-10-20 00:00?
谢谢。
答案 0 :(得分:1)
以下是如何使用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
答案 1 :(得分:1)
您可以使用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
答案 2 :(得分:1)
使用Calendar
API,如下所示 -
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());
输出:
Tue Oct 23 22:34:25 CDT 2012