So I'm trying to figure out what I'm doing wrong with this logic. It seems straightforward and my breakpoints indicate that the evaulation in the 'if' statement is resolving as True, but sum.ppStart et al aren't getting 14 days added to them.
It's probably something simple, but any help would be appreciated.
//Determine the start/end days of each week of the pay period and retrieve a list of those entries
DateTime[] weeks = timeTools.calcPP(0);
DateTime today = DateTime.Now.Date;
if (today > weeks[3])
{
weeks[0].AddDays(14);
weeks[3].AddDays(14);
weeks[4].AddDays(14);
}
sum.ppStart = weeks[0];
sum.ppEnd = weeks[3];
sum.payDate = weeks[4];
AddDays returns a new instance of DateTime, the existing value is not changed, it is an immutable structure. When using the function, capture the result
DateTime myDate = ...
myDate = myDate.AddDays(14);
That is because you're not using the result of the AddDays method. The signature is
public DateTime AddDays(double days)
or so (see link). You need to do this:
weeks[0] = weeks[0].AddDays(14);
You need to assign the values:
if (today > weeks[3])
{
weeks[0] = weeks[0].AddDays(14);
weeks[3] = weeks[3].AddDays(14);
weeks[4] = weeks[4].AddDays(14);
}
Related
I want to extract the name of the day as string from this:
Holder.CurrentDate = DateTime.Now.AddDays(countNext).ToLongDateString();
Holder.CurrentDay = ?
Where Holder.CurrentDay is a string. I have tried:
Holder.CurrentDay = Holder.CurrentDate.DayOfWeek.ToString();
But DayOfWeek does not exist as a function in this context. Do you guys have any ideas how I can accomplish this?
You could just do this:
var CurrentDate = DateTime.Now.AddDays( 4 ).ToLongDateString();
var CurrentDay = Convert.ToDateTime(CurrentDate).DayOfWeek.ToString();
But its better to store the DateTime itself in a variable instead of converting it back:
var theDateWeNeed = DateTime.Now.AddDays( 4 );
//Now we can do this:
Holder.CurrentDate = theDateWeNeed.ToLongDateString();
Holder.CurrentDay = theDateWeNeed.DayOfWeek.ToString();
You would be better to use ToString with a format pattern if what you ultimately want is a string. Then you have control over language, etc.
Use the "dddd" pattern to get the name of the day of the week.
var dayOfWeek = DateTime.Now.ToString("dddd");
Pass a second CultureInfo parameter if you want it in a specific language.
I found a way, sorry...
Holder.CurrentDay = DateTime.Now.AddDays(countNext).DayOfWeek.ToString();
You cannot invoke DayOfWeek on string. i.e. you have to convert it back or use the same DateTime as you did in your previous statement.
Holder.CurrentDay = DateTime.Now.AddDays(countNext).DayOfWeek.ToString();
I am trying to set a variable that calculates the date six months prior to today's date.
string exampleDate = (DateTime.TodaysDate) - (00/06/00)
Or something like that... I know the above definitely does not work.
I would be grateful for any ideas.
Thanks
DateTime date = DateTime.Now.AddMonths(-6);
// if you want to convert to string:
string myDate = date.ToString();
Simply:
var sixMonthsPriorToNow = DateTime.Now.AddMonths(-6);
I am writing a program in c# and I need to do some math with dates. I need to let the user enter a date, calculate the date that is 91 days later, and then find the month right after that. ex: user enters date of 1/15/12, it should add 91 days, 4/15/12, and then return a date of 5/1/12. Unfortunately, I have no idea how to do this and I couldn't find anything that was helpful.
var oldDate = <your_datetime_variable>.AddDays(91);
var newDate = new DateTime(oldDate.Year, oldDate.Month, 1).AddMonths(1);
Since constructing a new DateTime object has been suggested, here is another approach:
DateTime when = <user_supplied_date>;
DateTime future = when.AddDays(91);
when = future.AddDays(-(future.Day - 1)).AddMonths(1);
This is a little cryptic, but results in a one-liner that you could use.
I'm writing a service but I want to have config settings to make sure that the service does not run within a certain time window on one day of the week. eg Mondays between 17:00 and 19:00.
Is it possible to create a datetime that represents any monday so I can have one App config key for DontProcessStartTime and one for DontProcessEndTime with a values like "Monday 17:00" and "Monday 19:00"?
Otherwise I assume I'll have to have separate keys for the day and time for start and end of the time window.
Any thoughts?
thanks
You could use a utility that will parse your weekday text into a System.DayOfWeek enumeration, example here. You can then use the Enum in a comparison against the DateTime.Now.DayOfWeek
You can save the day of the week and start hour and endhour in your config file, and then use a function similar to the following:
public bool ShouldRun(DateTime dateToCheck)
{
//These should be read from your config file:
var day = DayOfWeek.Monday;
var start = 17;
var end = 19;
return !dateToCheck.DayOfWeek == day &&
!(dateToCheck.Hour >= start && dateToCheck.Hour < end);
}
You can use DayOfTheWeek property of the DateTime.
And to check proper time you can use DateTime.Today (returns date-time set to today with time set to 00:00:00) and add to it necessary amount of hours and minutes.
The DateTime object cannot handle a value that means all mondays. It would have to be a specific Monday. There is a DayOfWeek enumeration. Another object that may help you is a TimeSpan object. You could use the DayOfWeek combined with TimeSpan to tell you when to start, then use another TimeSpan to tell you how long
This is very rough code, but illustrates that you can check a DateTime object containing the current time as you wish to do:
protected bool IsOkToRunNow()
{
bool result = false;
DateTime currentTime = DateTime.Now;
if (currentTime.DayOfWeek != DayOfWeek.Monday && (currentTime.Hour <= 17 || currentTime.Hour >= 19))
{
result = true;
}
return result;
}
I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
Can you help me? I need your cool algorithm :) Thanks again...
myDateTimeVariable.Add(new TimeSpan(2,2,2));
If you choose to use the TimeSpan, be aware about the Days part:
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
With DateTime:
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10:00
Adding two datetimes from strings:
var result = DateTime.Parse(firstDate) + DateTime.Parse(secondDate);
Adding a string time to a datetime:
var result = existingDateTime.Add(TimeSpan.Parse(stringTime);
Adding time as in your example:
var result = TimeSpan.Parse("12:30:22") + TimeSpan.Parse("11:20:22");
Finally, your example as dates (not tested!):
var result = DateTime.Parse("12:30:22") + DateTime.Parse("11:20:22");
Note that this is sloppy coding, but you get the idea. You need to verify somehow that the string is actually parseable.
Not really sure what you're after, but can you not just use the built in functions to C#'s DateTime object?
DateTime myDate = DateTime.Now;
myDate = myDate.AddHours(1);
myDate = myDate.AddMinutes(30);
myDate = myDate.AddSeconds(45);
The problem is more abstract. As already mentioned, in .NET there are two types - DateTime and TimeSpan. The DateTime type represents a specific point in time. It's not an interval of time. It's a specific location in all time since the birth of the Universe. Even if you set the year/month/day components to 0, it will still represent some absolute point in time. Not a length of time.
The TimeSpan on the other hand represents some interval. 1 minute, 2 days, whatever. It's not specified WHEN, just HOW LONG.
So if you were to subtract two DateTime objects you would get a TimeSpan object that specifies how much time there is between them. And if you add a TimeSpan to a DateTime you get another DateTime. But you can't add a DateTime to another DateTime - that would make no sense.
It sounds to me like you should be working with TimeSpans all the time, because you are dealing with lengths of time, not absolute points in time. If you get these lengths from your source as a DateTime then that's actually not correct, and you should convert them to TimeSpans somehow. The parsing method is one way that has been suggested, but you might also try to subtract zero DateTime from it. That might be faster and more culture-independant.
use the TimeSpan structure. you can add TimeSpans together, or you can add a TimeSpan to a DateTime to produce a new DateTime.
You should have a look at TimeSpan.Parse. This converts a string to a TimeSpan object. That way you can do stuff like
TimeSpan a = TimeSpan.Parse(timeStringA)+TimeSpan.Parse(TimeStringB);
To split a string like "00:00:20+00:01:00" look at string.split
stringA = timeSting.split('+')[0];
stringb = timeSting.split('+')[1];
return string.Format("{0}:{1}:{2}", mytimespan.Hours
+ (mytimespan.Days*24),mytimespan.Minutes,mytimespan.Seconds);
static void Main(string[] args)
{
String timeText = "3/23/2015 12:00:13 AM";
String timeText2 = "3/23/2015 1:45:03 AM";
DateTime time = Convert.ToDateTime(timeText);
string temp = time.ToString("HH:mm:ss");
DateTime time2 = Convert.ToDateTime(timeText2);
string temp2 = time2.ToString("HH:mm:ss");
TimeSpan t1 = TimeSpan.Parse(temp);
TimeSpan t2 = TimeSpan.Parse(temp2);
Console.Out.WriteLine(t1 + t2); // 01:45:16
Console.ReadLine();
}