I'm using Date.wday to get the weekday number, but then how can I create a new Date with just that number (without using Date.commercial)? I only need the date to be next week's. For example, if I have 2 (Tuesday), the new date would be whatever date next tuesday is (2009-07-28). Thanks!
I doubt you can accomplish something like that, as you can imagine...
creating a new Date object implicity says, creating a Date, and not a weekday...
why not get that day and add a week to it?
create a method that passes the date and the weekday, then add days until you get the weekday you need and add 1 week to get the next week if you need.
(sorry, I'm a C# develop, but I hope you get what I'm saying)
DateTime AddWeekFromDate(DateTime today, DayOfWeek week)
{
if(today.DayOfWeek == week)
return today.AddDays(7);
while (today.DayOfWeek != week)
today = today.AddDays(1);
return today;
}
using
lbl.Text = AddWeekFromDate(DateTime.Now, DayOfWeek.Wednesday).ToLongDateString();
sing the date today (July 23rd 2009) it outputs
Wednesday July 29th, 2009
I don't know anything about Java, but I do a lot of date stuff in other languages. If you know it's always going to be a week away, you could have something that always figures out what this week's Monday is, and then based on that, add your day of the week number and 7 to the date. So in PHP, I'd go with:
$monday = (date('w', time()) == 1) ? strtotime("Today") : strtotime("Monday");
// This will give us a date variable of this Monday. The conditional bit is to avoid getting last Monday when today is Monday.
$day_number = $_POST['daynumb'];
// Or however the day of the week number gets into the mix.
$next_week = strtotime("+".$day_number + 7." days", $monday);
I know this isn't perfect in terms of syntax and what you need, but logically it should work out the same way.
You can turn a day number (e.g. 2
) into a day name as follows:
day_number = 2
Date::DAYNAMES[day_number]
# => 'Tuesday'
If you install the chronic gem, then you can do nice natural-language parsing of Dates and Times. For example:
Chronic.parse 'next tuesday' # it's currently Thursday, July 23
# => Tue Jul 28
Combining them, you can do
require 'chronic'
class MyClass
# returns a Date for the nth day of the week next week
def next_n_day(n)
Chronic.parse("next #{Date::DAYNAMES[n]}")
end
end
Find the delta of days between next Tuesday and today, then use Date#+
today = Date.today
future_wday = 2
delta_days = future_wday + 7 - today.wday
future_date = today + delta_days
p future_date.ctime # => "Tue Jul 28 00:00:00 2009"