I have the value DPIYRMO type: Int
My goal is to take this value and create an if statement where it compares the current month, to the month that the user sets DPIYRMO to.
Example, the user sets DPIYRMO to November, if this happens, I will have a messagebox that lets them know that their DPIYRMO is set to that month and not the current month.
This if statement will be placed in here:
private void OnPostCertificate()
{
if (TaxCertificateList.Where(c => c.IsSelected).Count() == 0)
return;
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoPost);
bw.RunWorkerCompleted += BwOnRunPostCompleted;
bw.RunWorkerAsync();
}
I believe I may have to use substrings, however, I am not sure where to start.
Don't you simply want something like that?
if (obj.DPIYRMO != DateTime.Now.Month)
{
string dpiyrmoMonth = new DateTime(1970, obj.DPIYRMO, 1).ToString("MMMM");
Console.WriteLine(dpiyrmoMonth + " does not match the current month.");
// prints March does not match the current month.
}
DateTime.Now returns the current date and time, and the Month property returns the month as an integer: 1 for January, 2 for February... So you can compare it to your integer variable.
new DateTime(1970, obj.DPIYRMO, 1) returns a date with the month part equals to the one stored in your integer variable. Note that the year 1970 and the 1st day of the month are arbitrary values for the use we do, because ToString("MMMM") returns the month part formatted in a human-readable string. See the format you can use.
Related
This is for a program at work. I don't have access to the code right now, but I really want to figure this out, so I wrote a quick program at home that is a mimic of my work project.
I need to know if that date is within 3 working days of a "holiday". If it is, then the selected date must be incremented by one to skip over the holiday. Example:
If there is a holiday on "01/19/2018" and a user selects "01/16/2018", then the program must skip the 19th and then set the closing date as "01/20/2018". Now if I do pure if/then statements, I can get it to work as expected, but the problem then becomes: "what if both 01/19/2018 AND 01/20/2018 are holidays?" This is where I'm stuck.
At work, I'm using a SQL table that already has a column for dates in "MM/dd/yyyy" format (so those dates are my list source that I am checking against.) The user opens a calendar and selects a date. I'm actually parsing an XML file that is created by another method that actually touches the database then using XElement for an iteration that puts all those dates in a string list.)
This is the code in my pseudo work program:
private void button1_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
txtLog.Text = dt.ToString("MM/dd/yy") + Environment.NewLine;
List<string> allexemptdays = new List<string>();
string[] days = { "11/19/2018", "11/20/2018" };
foreach (string a in days)
{
allexemptdays.Add(a);
}
foreach (string a in allexemptdays)
{
ToLog(a);
}
DateTime eq = DateTime.Parse(txtDate.Text);
string thefrustrationisreal = eq.ToString("MM/dd/yy");
if (Math.Abs(DateTime.Now.Subtract(eq).Days) <= 3)
{
MessageBox.Show("Date exemption found.");
}
}
private void ToLog(string a)
{
txtLog.Text += ("Array value to list: " + a + Environment.NewLine);
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
txtDate.Text = monthCalendar1.SelectionStart.ToString("MM/dd/yy");
}
Obviously I understand "DateTime.Now" doesn't reflect what I require, but I was just playing more with the DateTime class.
So in short: I'm creating an array with the dates (similar to my real program)
Iterating through them, adding them to a list. Now I need to check if the selected date falls within 3 days of the predefined date from a returned value from my sql table.
If a date is found, move the closing date up a day; however, if holidays in a row are found, then skip those two dates altogether. I can do this on a one by one basis (using if/then) but this doesn't work well if two holidays are back to back of each other.
As a side note, I want to be able to tell if the selected date is within 3 days AND moves over to another month, but I think I can handle that with DateTime, checking the days in a month and incrementing when needed (or I'm sure DateTime could do that for me actually.) I'm not too worried about this concern though at this point.
I did accept Mike's answer as it does work as intended, but! I now have a different issue
Now the "days.count()" holds a persistent number after the user selects a date beyond the holidays. Example: Selecting January 21 2017 returns "Janurary 26 2017" as the closing date because it's still counting the 20th and 21st as holidays affected by the range, when it should just set the closing date now at "Janurary 24th 2017"
I've played around with the code provided; I can't find a good way to fix it. I was thinking something along the lines of:
If(selectedDate.AddDays(3) >= holidaydate) then do a check for another day through the datetime list, but I'd still be making that way more complicated than it should be (I think.)
Last entry I'll do to this post (I'm considering this post solved now):
Matt's answer I selected does work to an extent and I appreciate his help. Problem is, the .Count() never resets, so if you go past the holiday(s) dates, it always holds onto the skipped days (so instead of going to 3 days ahead of the selected date, it'll go (3+the total number of days counted))
In the event someone else comes across a situation like this, here's what I ended up doing:
Downloaded the "WorkingDaysManagement" reference, instructions from:
https://github.com/Opturne/WorkingDaysManagement
the code I ultimately used is:
private void button1_Click(object sender, EventArgs e)
{
txtLog.Text = null;
DateTime dt = DateTime.Now;
var sd = (DateTime.Parse(txtDate.Text));
Console.WriteLine(sd.ToShortDateString());
var listHolidays = new List<DateTime>
{
new DateTime(2017, 12, 24),
new DateTime(2017, 12, 25)
};
var listWeekEnd = new List<DayOfWeek>
{
DayOfWeek.Saturday,
DayOfWeek.Sunday
};
var helper = new WorkingDayHelper(listHolidays,listWeekEnd);
foreach(DateTime s in helper.GetSpanDates(sd,3))
{
Console.WriteLine("Current iteration date: "+s.ToShortDateString());
}
var nextworkday = (helper.GetSpanDates(sd, 3).Last().ToString());
txtLog.Text += ("Next working day available: " + nextworkday + Environment.NewLine);
if(helper.IsWorkingDay(sd)==true)
{
txtLog.Text += ("It is a working a day." + Environment.NewLine);
}
else
{
txtLog.Text += ("NOT a working day!" + Environment.NewLine);
}
txtEndDate.Text = nextworkday;
}
The author of the plugin was gracious enough to put his work under the MIT license as well.
Let's say you have parsed all the date strings from the database into a List<DateTime> namely holidays. Then you can do something like
// Parsed holidays in a list, we will use LINQ against it.
var holidays = new List<DateTime> {
new DateTime(2017, 1, 19),
new DateTime(2017, 1, 20),
};
// Selected Date. In your case it would be: DateTime.Parse(txtDate.Text);
var selectedDate = new DateTime(2017, 1, 16);
// Count how many holidays there are within 3 days from the selcted date.
var count = holidays.Count(holiday => holiday - selectedDate <= TimeSpan.FromDays(3));
// Then add the count and 3 to the selected date
var closingDate = selectedDate.AddDays(count + 3);
// Now we have to make sure the closing date is not a holiday.
if (count > 0)
{
int skipDays = 0;
while (holidays.Any(holiday => holiday == closingDate.AddDays(skipDays)))
{
// holidays list contains the date. Skip it.
skipDays++;
}
closingDate = closingDate.AddDays(skipDays);
}
I want to convert digit month that is inputed by User to the name of month. I find it easily to use if else condition, but is there any function I can use without using condition? It's take me to write alot of code.
Note : Just month!
int month = 0;
bool TempResult = false;
Console.Write("Month: ");
TempResult = int.TryParse(Console.ReadLine(), out Month);
There are two reasonably simple options:
Construct a date using that number as the month, and then format it with a custom format, e.g.
DateTime date = new DateTime(2000, month, 1);
string monthName = date.ToString("MMMM");
Use DateTimeFormatInfo.MonthNames
DateTimeFormatInfo info = CultureInfo.CurrentCulture.DateTimeFormat;
// The array is 0-based, e.g. MonthNames[0] is for January
string monthName = info.MonthNames[month - 1];
Both of these will take the name from the current culture; in either case you can specify a different CultureInfo if you want. (In the first case, use it as a second argument to ToString.)
I have a date value that I want to strip the time from. I want the return type to be a date type since I want to order the list of date I have. having a list to string representing Date does not return a correct order.
I know that DateTime always returns the date with the time. What are my options here? How can I better my code and have a list of items of Date type without the time?
Edit: I would like to have the date only. nothing after that. Something like 8/7/2016 not 8/7/2016 00:00:00 or anything after date. and in a date object.
Here is my code:
using (var db = new MyModel.Context())
{
var cert = (
from tr in db.uspTranscripts(personId)
from a in db.PersonTranscripts.Where(x => x.UPID == personId)
from b in db.LU_CreditType.Where(x => x.ID == a.CreditTypeID)
select new CertViewModel
{
ActivityTitle = tr.ActivityTitle,
Score = tr.Score,
Status = tr.Status,
CompletionDate = tr.CompletionDate,
CretitTypeName = b.ShortName,
CompletedDateSorted = a.HK_CreatedOn
}).OrderByDescending(x => x.CompletedDateSorted).ToList();
List<CertViewModel> certlist = cert;
foreach (var item in certlist)
{
string itemWithoutHour = item.CompletionDate.Value.ToShortDateString();
var itemConverted = DateTime.ParseExact(itemWithoutHour, "M/d/yyyy", null);
item.CompletionDate = itemConverted;
}
return certificateslist.GroupBy(x => x.ActivityTitle).Select(e => e.First()).ToList();
}
For any given DateTime object, you can reference its Date property to strip out the time values:
var withTime = DateTime.Now; // 8/7/2016 22:11:43
var withoutTime = withTime.Date; // 8/7/2016 00:00:00
The .NET framework does not have a date-only object.
It may be worth understanding how the DateTime structure works. Internally, it stores an offset in ticks (1 tick = 100 nanoseconds) since 1/01/0001 12:00 am in a single 64-bit unsigned integer. (1 tick = 100 nanoseconds)
The DateTime structure then provides many useful methods and properties for dealing with dates and times, such as adding some days to an existing date, or calculating the difference of two times. One useful property is Date, which rounds a DateTime object down to the nearest day (12:00 am).
Dates, times and dates-with-times are all very similar, the main difference is how you format them, a date-with-time where you omit the time is just a date.
What David has suggested is that you work with the DateTime structure internally, strip any times using the Date property, sort on the DateTime, compare them and modify them as DateTime objects.
Only convert them to a string when they need to be displayed, at which point you can use methods such as ToShortDateString() or ToString(string format) to display only the date.
I have to thank for the early help to advise the "Tick". Now am pretty much got in to my logic except one thing, i have a unix time in my database ,when i was trying to convert to real time and do the logic.
Sorry, let me describe the problem once again,
I have four different timestamp pulled out from DB (Start,End,Start1,End1) converted from unix to real time. am using the following code to do the conversion
DateTime = Convert.ToDateTime("1/1/1970").AddSeconds(SnapTo5Mins(Convert.ToDouble(UnixDate))).AddHours(GMTOFFset);
Problem here is,when the value is zero in the coloumn then the date time is returning like (1/1/1970).
for eg. my start value is zero in the database then it retruns (1/1/1970)
Step 1: compare the timestamp is not equal to 1/1/1970 (origin time)
step 2: if its not equal then do Break = End.Subtract(Start); Step
3: if its equal then assign the break value to zero or whatever step
4: repeat step 1,2,3 for start1 step 5: concatenate both break +
break1
DateTime Origin = new DateTime(1970, 1, 1, 12, 0, 0, 0);
DateTime Start ="01/01/1970 12:00";
DateTime End = 01/01/1970 12:00";
DateTime Start1 ="02/10/2013 12:20";
DateTime End1 = "02/10/2013 02:20";
TimeSpan Break;,finalMealBreak1;
if (Origin.Year != Start.Year)
{
Break = End.Subtract(Start);
}
else
{
Break = //Assign constant value zero
}
if (Origin.Year != Start1.Year)
{
Break1 = End1.Subtract(Start1);//break1 value must be 2hrs
}
else
{
Break1 = //Assign constant value zero
}
TimeSpan FinalBreakResult = Break + Break1; (FinalBreakresult value suppose to be 2 hrs )
Thanks in advance
Not 100% sure what you are trying to get from the timespan, I think 0? But you can do a few things to get values.
TimeSpan.Zero // timespan of 0
DateTime.Now.TimeOfDay // returns a value of the current time in a timespan
// obviously also works with any datetime
TimeSpan.FromSeconds(100) // timespan with 100 seconds
// There are a few of these, like FromHours, FromDays
Edit: Using your code
DateTime Origin = new DateTime(1970, 1, 1, 12, 0, 0, 0);
DateTime Start = DateTime.Parse("01/01/1970 12:00:00");
DateTime End = DateTime.Parse("01/01/1970 12:00:00");
DateTime Start1 = DateTime.Parse("02/10/2013 12:20:00");
DateTime End1 = DateTime.Parse("02/10/2013 14:20:00");
TimeSpan Break, Break1;
if (Origin.Year != Start.Year)
{
Break = End.Subtract(Start);
}
else
{
Break = TimeSpan.Zero;
}
if (Origin.Year != Start1.Year)
{
Break1 = End1.Subtract(Start1);//break1 value must be 2hrs
}
else
{
Break1 = TimeSpan.Zero;
}
TimeSpan FinalBreakResult = Break + Break1;
// Value of FinalBreakResult is 2 hours
Of course. To add to #Dan Saltmer's answer:
DateTime then = DateTime.Now;
Thread.Sleep(500);
TimeSpan span = DateTime.Now - then;
I have a text field that will contain a given year, for example, "2011". I need to calculate the value of the year 70 years earlier.
I have this code already, which supplies a default value for the text box:
var LastYear = DateTime.Now.AddYears(-1).ToString("yyyy"); //"2011"
Yeartextbox.Text = LastYear;
The user is allowed to change the value of the text box to whatever year they want. I need to take the data from the text box, and calculate 70 years earlier. For example, if the text box contains "2011" I need the result of 1941; if the user enters 2000 I need the result of 1930.
What is stopping from you to read from the Textbox and Assign to a DateTime object and call the AddYears function ?
DateTime dateEntered=DateTime.Parse(Yeartextbox.Text);
var thatYear= dateEntered.AddYears(-70);
Yeartextbox.Text = thatYear.ToShortDateString();
You are storing a year into the text box, not a date. Just, for example, 2011. That's just a number, an integer, and you can do integer math on it. (The fact that it happens to be a year is irrelevant to the - operator.)
If you want to subtract 70 years from that, just do 2011 - 70:
var year = Int32.Parse(Yeartextbox.Text) - 70;
I'm not sure I understand....but is this what you're looking for....pre-poluting the text box with -70?
var LastYear = DateTime.Now.AddYears(-70).ToString("yyyy"); //"2011"
Yeartextbox.Text = LastYear;
Assuming you have two text boxes, here's how to do it:
// Get year as an integer from the text box
int currentYearAsInt = int.Parse(txtCurrentYear.Text);
// Create DateTime out of it (January 1st 1984, for example)
DateTime currentYear = new DateTime(currentYearAsInt, 1, 1);
// Create new DateTime 70 years older (remember, you cannot just call AddYears on the object, you have to assign returned value)
DateTime oldYear = currentYear.AddYears(-70);
// Populate new text box with old year's value (or do whatever you want with it
txtOldYear.Text = oldYear.Year.ToString();
Hope it helps.
For instance if they want this year, its going to be 2012-70
If i understand you correctly, you have problems to translate the year from the user to a DateTime object.
So if the user entered f.e 2005 you want 1935-01-01. Am i right?
This would work:
var input = "2005"; // Yeartextbox.Text
int year = 0;
DateTime result;
if(int.TryParse(input, out year))
{
result = new DateTime(year, 1, 1).AddYears(-70); //1935-01-01
}
string initialYear = "2011";
int year;
string calculatedYear;
if (int.TryParse(initialYear, out year))
{
var initialDate = new DateTime(year, 1, 1);
calculatedYear = initialDate.AddYears(-70).Year.ToString();
}
else
{
// Handle error since no valid value was entered
}
This will do the work (you obviously need to adapt it to your code). If it doesn't you might need to assure that the screen is correctly refreshed.