How to split a value and increment a part using c# - c#

I have the following code:
int value = 0;
int day = 0;
int record = db.Orders.Where(x => x.Order_Date.Value.Year == DateTime.Now.Year
&& x.Order_Date.Value.Month == DateTime.Now.Month
&& x.Order_Date.Value.Day == DateTime.Now.Day).Count();
if (record > 0)
{
value = int.Parse(db.Orders.OrderByDescending(x => x.Order_Id).Select(y => y.Order_Id).First().ToString());
value += 1;
}
else
{
day = Convert.ToInt32(DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
value = day + 0001;
}
I want to save the order id in ddmmyysomevalue like 0501150001 if it is first order.
I do have above code but how to split 0501150001 like 050115 and 0001 and then increment 0002 for the next order and make it 0501150000 thereby 0501150009 to 0501150010 and make the above code meaningful.

You have to store value in string.
For number you have to use format like this.
int value = 1;
String finalnumber = DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy") + value.ToString("0000");
Console.WriteLine(value.ToString("0000")); // to format number only.
// to get as a number
long finalnumber = Convert.ToInt64( DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy") + value.ToString("0000"));

Because the code you've shown will always have the same length for each part of the Order Id you can split by length and cast the final part to an integer. Bear in mind this will break if any part of the orderId starts using a different length in future:
// get the date part of the string by length
string datePart = orderId.Substring(0, 6);
// get the count part of the string by length and cast to integer
int countPart = Int32.Parse(orderId.Substring(6, 4));
// increment the count
countPart++;
// convert the count back into a string and pad with zeroes to get length 4
string newCount = countPart.ToString().PadLeft(4, '0');
// combine with the datepart to get the new OrderId
string newOrderId = datePart + newCount;

This should point you in the right direction...
int existingTodayOrdersCount = db.Orders
.Where(x => x.Order_Date.Value.Date == DateTime.Now.Date)
.Count();
string newOrderId = string.Format(
"{0:yyMMdd}{1:0000}",
DateTime.Now,
existingTodayOrdersCount + 1);
When comparing two dates you can just call .Date on your DateTime objects. No need to explicitly compare the year, month and day
To concatenate numeric values or format a numeric value with leading zeros you need to treat it as a string
The above code uses a custom numeric format string (0000) and a custom date and time format string (yyMMdd).
Be aware of subtle bugs though...
What if you already have 9999 orders today?
What if this code is executed at midnight (could DateTime.Now wrap to the next day part way through execution?)
What if you delete an order record from the database, in which case newOrderId might clash with an existing order?

Related

Sum hours from different formatted dates. C#

I have a problem. I need to sum hours worked in an office in a code. The dates i get from SQL server thats no problem but i have different formats. For example: 2019. 09. 23. 14:54:23, 2019.09.23 14:54:23 or 2019-09-23 14:54:23; And i want to sum hours worked in result. No matter the year. Heres the example:
try
{
string betölt = "SELECT * from munkaorak where";
if (cbTech.Text != "")
{
betölt += " Munkaszam='" + cbMunka.Text + "' AND Részfolyamat='" + cbRész.Text + "' AND TechKod='" + cbTech.Text + "'";
}
else if (cbRész.Text != "")
{
betölt += " Munkaszam='" + cbMunka.Text + "' AND Részfolyamat='" + cbRész.Text + "'";
}
else if(cbMunka.Text !="")
{
betölt += " Munkaszam='" + cbMunka.Text + "'";
}
betölt += " order by ID DESC";
MySqlCommand name = new MySqlCommand(betölt, kapcsolat);
kapcsolat.Open();
olvasó = name.ExecuteReader();
int összora = 0;
if (olvasó.HasRows)
{
while (olvasó.Read())
{
if (olvasó.GetString(7) != "Befejezés: ")
{
string[] aha = olvasó.GetString(6).Split(' ');
string kezdes = aha[4];
string[] kezd = kezdes.Split(':');
int kezdoido = Convert.ToInt32(kezd[0]) * 60 * 60 + Convert.ToInt32(kezd[1]) * 60 + Convert.ToInt32(kezd[2]);
int befejezoido = 0;
string aha22 = "";
if (olvasó.GetString(7).IndexOf('-') >= 0)
{
string[] aha2 = olvasó.GetString(7).Split(' ');
string befejezes = aha2[1];
string[] bef = befejezes.Split(':');
aha22 = aha2[0].Split('-')[2];
befejezoido = Convert.ToInt32(bef[0]) * 60 * 60 + Convert.ToInt32(bef[1]) * 60 + Convert.ToInt32(bef[2]);
}
else
{
string[] aha2 = olvasó.GetString(7).Split(' ');
string befejezes = aha2[4];
string[] bef = befejezes.Split(':');
aha22 = aha2[3];
befejezoido = Convert.ToInt32(bef[0]) * 60 * 60 + Convert.ToInt32(bef[1]) * 60 + Convert.ToInt32(bef[2]);
}
string dolgozott = "";
if (aha[3].Replace(".", "") == aha22.Replace(".", ""))
{
dolgozott = mpbolora(befejezoido - kezdoido);
összora += befejezoido - kezdoido;
}
else
{
dolgozott = mpbolora((86400 - kezdoido) + befejezoido);
összora += (86400 - kezdoido) + befejezoido;
}
string validalo = "";
try
{
string[] validal = olvasó.GetString(9).Split(' ');
validalo = validal[0] + " " + validal[1] + " " + validal[2] + validal[3] + validal[4] + " " + validal[5];
}
catch
{
validalo = olvasó.GetString(9);
}
string munkafolyamat = olvasó.GetString(3) + "-" + olvasó.GetString(4) + "-" + olvasó.GetString(5);
string[] sorok = { olvasó.GetString(2), dolgozott, olvasó.GetString(6).Replace("Kezdés: ", ""), olvasó.GetString(7).Replace("Befejezés: ", ""), olvasó.GetString(8), validalo, munkafolyamat };
var lv = new ListViewItem(sorok);
lvStat.Items.Add(lv);
}
}
}
else
{
kapcsolat.Close();
MessageBox.Show("Nincs adat!", "Figyelem");
}
kapcsolat.Close();
lblÖssz.Text = "Összesen ledolgozott órák: " + mpbolora(összora);
}
catch (Exception a)
{
MessageBox.Show(a.Message);
kapcsolat.Close();
}
kapcsolat.Close();
It worked but when different formats appeared its not working because '-' or spaces. Please help!
In C#, there is a bunch of methods provided to convert strings that contain date times in many formats into a unified DateTime object. These methods can recognize quite a few standard date time formats, and if yours differ from them, you can even provide your own.
DateTime.Parse() - Converts a string to a DateTime object. If operation fails, it'll thrown an exception.
DateTime.TryParse() - Converts a string to a DateTime object only if possible. Returns true if successful, and false if it fails.
DateTime.TryParseExact() - Converts a string that is in the specified format into a DateTime object. Returns true if successful, and false otherwise.
In your case, you can use DateTime.TryParse() (which is recommended over simply using DateTime.Parse() unless you're absolutely sure the format is correct) like so:
var dtStr1 = " 2019. 09. 23. 14:54:23";
var dtStr2 = "2019.09.23 14:54:23";
var dtStr3 = "2019-09-23 14:54:23";
DateTime.TryParse(dtStr1, out DateTime dt1);
DateTime.TryParse(dtStr2, out DateTime dt2);
DateTime.TryParse(dtStr3, out DateTime dt3);
Once converted to a DateTime object, it no longer has a format associated with it. It's a structure, and hence only has member variables and methods. So to calculate total hours etc. you can use provided methods.
Say you want to calculate time between day's work start and end. You can convert those into DateTime objects, then subtract one from the others which will give you a TimeSpam object.
var dtStrStart = "2019.09.23 08:23:12";
var dtStrEnd = "2019.09.23 16:17:28";
DateTime.TryParse(dtStrStart, out DateTime dtStart);
DateTime.TryParse(dtStrEnd, out DateTime dtEnd);
var diff = dtEnd - dtStart;
Now the TimeSpan object, which is diff here, will give you a bunch of properties with difference in hours, minutes etc.
The TimeSpan.Days, TimeSpan.Minutes etc will give you the time in days, minutes etc.
Console.WriteLine(diff.Days);
Console.WriteLine(diff.Hours);
Console.WriteLine(diff.Minutes);
Console.WriteLine(diff.Seconds);
Console.WriteLine(diff.Milliseconds);
Output:
0
7
54
16
0
The TimeSpan.TotalMinutes etc will give you the entire time period in respective units.
Console.WriteLine(diff.TotalDays);
Console.WriteLine(diff.TotalHours);
Console.WriteLine(diff.TotalMinutes);
Console.WriteLine(diff.TotalSeconds);
Console.WriteLine(diff.TotalMilliseconds);
Output:
0.329351851851852
7.90444444444444
474.266666666667
28456
28456000
And conversely, when you're storing data in the database, you must again use a standard format, such as datetime or datetime2. It's advised you use datetime2, more info here.
Your code should look more like this:
try
{
MySqlCommand name = new MySqlCommand("SELECT * from munkaorak WHERE Munkaszam=#m", kapcsolat);
name.Parameters.AddWithValue("#m", cbMunka.Text);
if (cbRész.Text != "")
{
name.CommandText += " AND Részfolyamat=#r";
name.Parameters.AddWithValue("#r", cbRész.Text);
}
if (cbTech.Text != "")
{
name.CommandText += " AND TechKod=#t";
name.Parameters.AddWithValue("#t", cbTech.Text);
}
name.CommandText += " order by ID DESC"; //is it really necessary?
MySqlDataAdapter da = new MySqlDataAdapter(name);
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow ro in dt.Rows){
string fromStr = ro["YOUR_FROM_DATE_COLUMN_NAME"].ToString();
//cope with dates in varying formats
//by replacing all non-numeric chars with nothing
fromStr = Regex.Replace(fromStr, #"[^0-9]", "");
//now our dates of [2019. 09. 23. 14:54:23], [2019.09.23 14:54:23] or [2019-09-23 14:54:23]
//just become 20190923145423
DateTime fromDt = DateTime.ParseExact(fromStr, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
string toStr = ro["YOUR_TO_DATE_COLUMN_NAME"].ToString();
toStr = Regex.Replace(toStr, #"[^0-9]", "");
DateTime toDt = DateTime.ParseExact(toStr, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
//total hours worked
(toDt - fromDt).TotalHours;
}
}
Hopefully that looks a lot simpler
Here you see no..:
Risky SQL injection hack possibility - don't concatenate values into your SQL, ever. Always concatenate a parameter in and then give a value to the parameter. Always
Difficult to read, lengthy string concatenation - looks terrible, always avoid it if you can
DB Connection opening and closing - micromanaging the database connection isn't necessary when using a dataadapter because it opens and closes for you
DataReader code full of magic numbers - GetString(7), hmmm.. was that the time in or time out? GetInt(4) - was it the age? The year? Here we get rid of all the datareader GetXX calls with their column ordinals and fill a DataTable (something like a 2D array) with rows that can be indexed by string names. It's still not as good as it can be (strongly typed DataTables are better) but it's a huge leap better than filling code with magic numbers, and working with everything in the most obscure, weakly typed way possible
Awkward time handling - it's gone in favour of Date parsing, because pulling strings to bits number by number, converting them to int, multiplying them by seconds and hours so they can be manipulated is tedious and hard to read - do away with it all by parsing these strings to the data types that they should have been stored as in the first place; you need to record the date and times that things happen at. Try your best to get that DB converted so these things are stored properly, and until then convert your strings to DateTime
Diffing dates using seconds: utilising TimeSpan calculations means no need to convert things to seconds, do crude math, drop all notions of time zones, or daylight savings changes etc; by using dates subtracted from each other you get a time period between those dates that takes things like daylight saving clock changes into account. Or even the ability to have one date that is tomorrow, or X days into the future. Might not matter for this app, but one day it could..
If you have MySQL 8 you can do the regex replace in the DB. Could even get the DB to diff and sum the dates.. We can't really make any recommendations on this point though because we don't know the column names

Compare two values and get data in between them

I have two variables 2016-V-0049 and 2016-V-0070. Is there a way in which I can compare them and get all the missing data between them while comparing the last numbers. So in this case I want the result to be 2016-V-0050,2016-V-0051,2016-V-0052...etc.
Also can I have repeatable patterns like comparing 2016P13 and 2016P25(NumberWordNumber) and getting the missing numbers in between.
Sorry for not including what I have tried. Here's what I did and which works. I was just looking for more patterns which are generic.
string s = "2016-s-89";
string p = "2016-s-95";
var start = Convert.ToInt32(Regex.Match(s, #"\d+$").Value) +1;
var end = Convert.ToInt32(Regex.Match(p, #"\d+$").Value);
var index = Regex.Match(s, #"\d+$").Index;
string data = s.Substring(0, index);
List<string> newCases = new List<string>();
while (start < end)
{
string newCaseNumber = string.Format("{0}{1}", data, start);
newCases.Add(newCaseNumber);
start++;
}
Once you can define step by step what you actually want your code to do, the implementation is trivial to research and put together. In steps, you want this:
Parse the input string denoting the starting number, so you can obtain the numeric part you're interested in.
Now you have a numeric string, but it's still a string. Parse it to an integer so you can later perform arithmetic operations on it, such as incrementing it by one.
Repeat 1 & 2 for the string denoting the ending number.
Loop over the numbers between the start and end number, and rebuild the original string with the new number.
A naive implementation to do that looks like this:
string inputStart = "2016-V-0049";
string inputEnd = "2016-V-0070";
string pattern = #"[0-9]{4}\-[A-Z]{1}\-([0-9]{4})";
var regex = new Regex(pattern);
var match = regex.Match(inputStart);
var numberStart = int.Parse(match.Groups[1].Value);
match = regex.Match(inputEnd);
var numberEnd = int.Parse(match.Groups[1].Value);
for (int currentNumber = numberStart + 1; currentNumber < numberEnd; currentNumber++)
{
Console.WriteLine("2016-V-{0:0000}", currentNumber);
}
But this doesn't do input checking (start < end, start and end actually conforming to the pattern), doesn't support different patterns (the pattern and rebuild string are hardcoded) and assumes the "2016-V-" part of the string to always be the same.
You should use substring() function and convert to integer like this code:
var min = "2016-V-0049";
var max = "2016-V-0070";
var a = min.Substring(7);
var b = max.Substring(7);
int convertableVariable1 = int.Parse(a);
int convertableVariable2 = int.Parse(b);
for (int i = convertableVariable1; i < convertableVariable2; i++){
Console.WriteLine("2016-V-{0:0000}",i);
}
Console.WriteLine("Difference :{0}", convertableVariable2 - convertableVariable1);

How to add two time span values having negative sign in c#?

I have two columns in my table i-e Working Hours and Extra Hours for employee attendance and total time that employee has to work is nine (9) hours if somebody check in at 9 o ' clock and check out at 11 o ' clock then system automatically calculate his/her working hours and extra hours now in this case working hours will be 2 hours and extra hours will be in negative form e.g -7:00:00 hours because employee leave 7 hours before actual time and i stored this negative value as "varchar" in database for user facilitation to understand either employee worked more from given time or less.Now i need to add these extra hours of employee for creating summary of month but i don't know how to add these negative time span and when i convert it to timeofday format then system cannot convert it due to negative sign.
I calculate sum of working hours after reading it from database as:
wrkhrs=wrkhrs.Add(Convert.ToDateTime(dr["WorkHrs"].ToString()).TimeOfDay);
and i found some code for subtraction as:
TimeSpan exthrs = org_work.Subtract(tot_work);
but if timespan have negative sign then it don't work.
if any body have any idea then kindly share it . thanks in advance.
EDIT:
public Tuple<string,string> Calculate_Hours(int id,DateTime strt, DateTime end)
{
TimeSpan wrkhrs = new TimeSpan(0, 0, 0);
TimeSpan exthrs=new TimeSpan(0,0,0);
//select * from vw_Rept_Attend where UserID ='" + id + "' and convert(date,AtnDate) between '" + strt.Date + "' and '" + end.Date + "'
cmd = new SqlCommand("sp_Calculate_Hours_For_Report", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#startdate", strt.Date);
cmd.Parameters.AddWithValue("#end", end.Date);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["WorkHrs"].ToString().Length>0)
wrkhrs=wrkhrs.Add(Convert.ToDateTime(dr["WorkHrs"].ToString()).TimeOfDay);
if (!dr["ExtraHrs"].ToString().Contains("-") && dr["ExtraHrs"].ToString().Length > 0)
{
exthrs = exthrs.Add(Convert.ToDateTime(dr["ExtraHrs"].ToString()).TimeOfDay);
}
else if (dr["ExtraHrs"].ToString().Contains("-") && dr["ExtraHrs"].ToString().Length > 0)
{
string ext = dr["ExtraHrs"].ToString().Substring(dr["ExtraHrs"].ToString().LastIndexOf("-") +1);
exthrs = exthrs.Subtract(Convert.ToDateTime(ext).TimeOfDay);
}
}
conn.Close();
dr.Close();
return new Tuple<string, string>(string.Format("{0:00}:{1:00}:{2:00}", (int)TimeSpan.Parse(wrkhrs.ToString()).TotalHours, Math.Abs((int)TimeSpan.Parse(wrkhrs.ToString()).Minutes), Math.Abs((int)TimeSpan.Parse(wrkhrs.ToString()).Seconds)), string.Format("{0:00}:{1:00}:{2:00}", (int)TimeSpan.Parse(exthrs.ToString()).TotalHours, Math.Abs((int)TimeSpan.Parse(exthrs.ToString()).Minutes), Math.Abs((int)TimeSpan.Parse(exthrs.ToString()).Seconds)));
}
and called out put of above function as:
var mytuple = Calculate_Hours(id,Convert.ToDateTime(dtStart.Text), Convert.ToDateTime(dtEnd.Text));
string tot_workHrs= mytuple.Item1;
string tot_ExtHrs= mytuple.Item2;
above is my logic that i retrieve my correct output, if someone has any question then please feel free to ask me by creating new comment on this post.
hope now this will be helpful for all....
1.
Use TimeSpan.Duration():
https://msdn.microsoft.com/en-us/library/system.timespan.duration(v=vs.110).aspx
"Returns a new TimeSpan object whose value is the absolute value of
the current TimeSpan object"
2.
Or some code from HERE:
static string ToHMString(TimeSpan timespan) {
if (timespan.Ticks < 0) return "-" + ToHMString(timespan.Negate());
return timespan.TotalHours.ToString("#0") + ":" + timespan.Minutes.ToString("00");
}
Console.WriteLine(ToHMString(TimeSpan.FromHours(3))); //Prints "3:00"
Console.WriteLine(ToHMString(TimeSpan.FromHours(-27.75))); //Prints "-28:45"
First of all it is a bad idea to store a time/duration value as string in the database.
Second the .Net TimeSpan structure is perfectly able to represent negative durations and calculate with these correctly.
Suggestions:
Store your negative duration as a time/duration value in the databese. If your database has no duration type which supports negative values add a boolean "This value is negative"
In your C# code use TimeSpan and the usual operators: +and -
Does this do what you need?
string[] sample = new string[] { "2.1", "-7.0", "1.0" };
TimeSpan total =
sample
.Select(s => TimeSpan.FromHours(double.Parse(s)))
.Aggregate((ts0, ts1) => ts0.Add(ts1));
The total I get is -03:54:00 as a TimeSpan.

C# If statement where date is this month

string month = DateTime.Now.Month.ToString();
string CommandText = "SELECT slocref.slocname, partstuff.quantity, partstuff.currency, partstuff.postingdate" + " FROM partstuff INNER JOIN slocref ON partstuff.sloc = slocref.slocvalue";
This is the code to get date and month.
if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))
{
if (rdr["slocname"].ToString() == "Answer/Slatwall")
{
string quantity = rdr["quantity"].ToString();
string currency = rdr["currency"].ToString();
answertotalmonth += float.Parse(currency);
label100.Text = "$" + answertotalmonth.ToString("#,##0.00");
}
}
This is just an example of the code that is run by the if statement.
But the if statement needs to get all of the July information and add it up. So from 07/01/2012 to 07/31/2012. I cannot change the SQL because it messes up the rest of the program. I tried to get the current date, add the 0 in front of it, then use a wildcard.
Need a little direction on this if statement.
Let me clarify this post. The "postingdate" value comes from FileHelpers. Importing a text file by fixed width into these values. The postingdate value looks like "07/16/12"
So, I want to get this current month, and then if a postingdate value has that month's value, run the if statement code.
Why would you do this?
if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))
If rdr["postingdate"] is supposed to be a date, convert it to a date time and do a sensible comparison.
if(DateTime.TryParse(rdr["postingdate"].ToString(), rdrDateTime))
{
// proceed as planned
if (rdrDate.Month == DateTime.Now.Month)
{
// and so on.
}
}
Not sure I understand you problem correctly but why don't you just match the DataTime's month property:
if( date.Month == month)
{
//your code...
}
Also like mentioned above, you can parse the text as a date. But if you are just interested in just the month that may not be necessary.
Edit: As mentioned in the comments, you would have to check the year as well. So it would be better to pares as a full DateTime object.

How do I write a loop that prints this kind of text regarding date differences?

I need to generate a code where i will be getting an user input (an int) and using that i need to generate days of the week
example: user inputs - 5
I need to output something like below
Today is (todays date)
Tomorrow is (tomorrows date)
Day after tomorrow is
two days after tomorrow is
three days after tomorrow is ...
and if the user enters 6 it should output 6days as above.
please help as i'm an novice in C#
Thanks alot
I won't write code for you. Would like to give some hints.
You can use DateTime class to find out the current date and time and it also provide methods which you can easily use to find what next day is and similar.
You can use While Loop as you said in Title or even For can work
You can take input from user through Console class if you are making console based app otherwise you can take input in some textbox.
For loop or while loop will run for current day plus number that user have entered minus 1
static void Main(string[] args)
{
days();
}
public static void days()
{
Console.Write("Please enter number : ");
int a = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < a; i++)
{
string strdays;
switch (i)
{
case 0:
strdays = ". Todays date is : ";
break;
case 1:
strdays = ". Tommorrows date is : ";
break;
case 2:
strdays = ". Day after tommorrows date is : ";
break;
default:
strdays = ". " + (i-1) + "Days after tommorrows date is : ";
break;
}
Console.WriteLine((i+1)+ strdays + System.DateTime.Now.AddDays(i));
}
Console.ReadLine();
}
hope this help u..
The pieces of code you will need:
Console.Write
Console.ReadLine
int.Parse (to convert the input to an integer)
DateTime.Today
DateTime.AddDays(zeroOrMoreDays)
DateTime.DayOfWeek (if you want Wednesday instead of 10/19/2011 12:00:00 AM)
Here is some pseudo-code:
Ask the user for the number of days (as a string)
Parse numberOfDays into an int
for i = 0 to numberOfDays:
write line: today.AddDays(i).DayOfWeek
You'll also need to do some tricks to get the natural language stuff to work, e.g. three days after tomorrow is.
I'd use a few extra if i == 0 else if i == 1 type statements to solve this, and fall back on a general <number> days after tomorrow after a certain point.
See this (closed) question for links on how to get that number: converting numbers in to words C#
Edit due to your comments on the question
# sblom ... nope for a web service i'm planning
Don't use Console stuff then.
Make this a method instead, and don't do the string/int.Parse stuff. Just take an int directly.
Build a result with a StringBuilder, and return a string, rather than printing out the result directly.
int diff=0;
while (diff < 5)
{
Console.WriteLine(DateTime.Now.AddDays(diff));
diff++;
}
Int32 numberOfDays = 5;
DateTime dt = DateTime.Now;
for (int i = 0; i < numberOfDays ; i++)
{
Console.WriteLine(dt.AddDays(i).DayOfWeek);
}
Hope it helps! =)
// num is number if days we'll loop through
int num = 5;
// gets the current date time - save it off. even though incrementing days, in other
// date incrementing functions (min, sec etc...) it's important to save off
DateTime now = DateTime.Now;
// init a countervar
int count = 0;
// loop until num times
while (count < num)
{
// add the current count number of days and print
// ++ after the variable increments it after calculating the new date
DateTime curr = now.AddDays(count++);
// output the value - it ends up calling .ToString() on date.
Console.WriteLine(curr);
}

Categories