Condition base on Week of year (weekly changing method) - c#

Im going to deploy some conditional method that changed weekly.
for example This is my old code :
DayOfWeek dow = DateTime.Now.DayOfWeek;
switch (dow)
{
case DayOfWeek.Friday:
///Do something
break;
case DayOfWeek.Monday:
///Do something
break;
case DayOfWeek.Saturday:
///Do something
break;
case DayOfWeek.Sunday:
///Do something
break;
case DayOfWeek.Thursday:
///Do something
break;
case DayOfWeek.Tuesday:
///Do something
break;
case DayOfWeek.Wednesday:
///Do something
break;
}
in above code if user calls my url in each day , it will get special answer based on that day.
now i wanna make another method like this :
Condition week 1
{
//function 1
}
Condition Week 2
{
//function 2
}
Condition Week 3
{
//function 3
}
Condition Week 4
{
//function 1
}
Condition Week 5
{
//function 2
}
..........
as u can see after week 3 i start to run/loop function 1 from start till week 6 , and this will continue
till end of year and after that.
should i achieve this goal by using "Calendar.GetWeekOfYear" ?
or should i use this method? :
DateTime myDT = DateTime.Now;
GregorianCalendar myCal = new GregorianCalendar();
if ((myCal.GetDayOfMonth(myDT) >= 1) && (myCal.GetDayOfMonth(myDT) < 8))
{
Function 1
}
else if ((myCal.GetDayOfMonth(myDT) >= 8) && (myCal.GetDayOfMonth(myDT) < 15))
{
Function 2
}
else if ((myCal.GetDayOfMonth(myDT) >= 15) && (myCal.GetDayOfMonth(myDT) < 22))
{
Function 3
}
else if ((myCal.GetDayOfMonth(myDT) >= 22) && (myCal.GetDayOfMonth(myDT) < 31))
{
Function 1
}

Use GetWeekOfYear. It gives you some nice flexibility, how the first week is defined, and what the first day of the week should be. Here's the MSDN documentation.
class Program
{
static void Main(string[] args)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar calendar = dfi.Calendar;
var week = calendar.GetWeekOfYear(DateTime.Now.AddDays(1), CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
Console.Write(week);
Console.ReadLine();
}
}

Related

Switch case goes to default except one case

when i tried to use the Switch case function, it goes always to the default message besides case 5:
private void btnCandlesLight_Click(object sender, EventArgs e)
{
int result;
result = Convert.ToInt32(textBox1.Text);
switch(result)
{
case 1:
day1.Start();
candlesOne();
break;
case 2:
day2.Start();
candlesTwo();
break;
case 3:
day3.Start();
candlesThree();
break;
case 4:
day4.Start();
candlesFour();
break;
case 5:
day5.Start();
candlesFive();
break;
case 6:
day6.Start();
candlesSix();
break;
case 7:
day7.Start();
candlesSeven();
break;
case 8:
day8.Start();
candlesEight();
break;
default:
MessageBox.Show("Enter new day");
break;
}
}
When I Enter the value 1 for example to the text box, the default case works, but only when I enter the value 5 it works perfectly.
If you want to see the difference between the function "candlesOne" to "candlesFive":
The "c" variable is a variable of the seconds. i tried to use a timer in a way of lighting up the candles every 2-3 seconds.
public void candlesOne()
{
firedmatch.Left = firedmatch.Left + 100;
if (c == 1)
{
candle1.Visible = true;
}
if (c == 3)
{
candle2.Visible = true;
}
}
and:
public void candlesFive()
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3)
{
candle2.Visible = true;
}
if(c == 5)
{
candle3.Visible = true;
}
if(c == 7)
{
candle4.Visible = true;
}
if(c == 11)
{
candle5.Visible = true;
}
}
I haven't found a mistake,
can you guys help me?
Thanks
Have you checked if you really get for example (int)1 as a result of the "1" input from your conversion?
On a broader scale, there is a lot of repetition in your code, you should consider refactoring it a little.
In your CandlesOne and CandlesFive methods, you use a c variable, no idea what that is or where it comes from. Those two methods (and probably the other CandlesXXX() do the same kind of things. Can't you remove complexity by generalizing the logic? Can the result used in your switch-case be passed as a parameter and used to trigger the numbers of c == X calls in the CandleXXX() methods?
This way you could remove the switch and lose a lot of complexity!
Edit
If you have further problems, consider creating a .NET Fiddle, I miss a lot of context in your code so I cannot efficiently help you here.
Some refactoring ideas for you:
// Somewhere else in your code, create a dictionary with your day1-day8 objects
var days = new Dictionary<int, Day>()
days[1] = day1;
...
days[8] = day8;
//Simplfiy your method
private void btnCandlesLight_Click(object sender, EventArgs e)
{
try
{
var dayIndex = Convert.ToInt32(textBox1.Text);
if(dayIndex > 0 && dayIndex <= 8)
{
days[dayIndex].Start(); //Get the corresponding day via its Key
LightUpCandles(dayIndex); //pass the key as a parameter
}
else
{
MessageBox.Show("Enter new day");
}
}
catch(InvalidCastException exception)
{
//Whatever you do when the textbox cannot be parsed
}
}
I still don't get what your candlesOne to five methods are really doing or why the method "candlesOne" lights up two candles (pay attention to the variable naming). I also don't get how this makes up some kind of timer... but here's a first potential refactoring for it anyway:
public void LightUpCandles(int dayIndex)
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3 && dayIndex > 1)
{
candle2.Visible = true;
}
if(c == 5 && dayIndex > 2)
{
candle3.Visible = true;
}
if(c == 7 && dayIndex > 3)
{
candle4.Visible = true;
}
if(c == 11 && dayIndex > 4)
{
candle5.Visible = true;
}
}
Your switch logic is correct which I tested with the following;
int result;
result = Convert.ToInt32(textBox1.Text);
switch (result)
{
case 1:
MessageBox.Show("1");
break;
case 2:
MessageBox.Show("2");
break;
case 3:
MessageBox.Show("3");
break;
case 4:
MessageBox.Show("4");
break;
case 5:
MessageBox.Show("5");
break;
case 6:
MessageBox.Show("6");
break;
case 7:
MessageBox.Show("7");
break;
case 8:
MessageBox.Show("8");
break;
default:
MessageBox.Show("Enter new day");
break;
}
If you don't get the same results I would perhaps look at making the message boxes above display the data type of the variable.
MessageBox.Show(result.GetType().ToString());

c# read the number of month and output the name of month

Im trying to write a C# console program to read in the number of a month and output the name of the month, and then ask the user if they want to know the number of days in that month and if so output the number of days. Assuming that there are no leap years and February ALWAYS has 28 days only.
Thanks in advance if anyone can help!!
EDIT:
This is what I have so far, I'm having trouble with the second half of the problem, I'm not sure how to ask the user if they want to know the days of the month and how to use a switch to output the number of days...
class MainClass
{
public static void Main (string[] args)
{
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine());
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
Console.WriteLine("The month is: " + newDate.ToString("MMMM"));
Console.WriteLine();
A simple switch case will do?
string input = Console.In.ReadLine();
int number = -1;
int.TryParse(input, out number);
switch (number)
{
case 1:
Console.Out.WriteLine("January");
break;
case 2:
Console.Out.WriteLine("February");
break;
case -1:
Console.Out.WriteLine("Please input a valid number");
break;
default:
Console.Out.WriteLine("There are only 12 months in a year");
break;
}
i take it this is enough to finish the rest of your code.
next time, please provide some code for what you have tried already, just asking for simple code usually gets you nowhere.
public static string getName(int i)
{
string[] names = { "jan", "feb", ... } // fill in the names
return names[i-1];
}
public static string getMonthName(int mounth)
{
DateTime dt = new DateTime(2000, mounth, 1);
return dt.ToString("M").Substring(0, dt.ToString("M").IndexOf(' '));
}
Based on your other related question that was closed as a duplicate of this one (https://stackoverflow.com/questions/24996241/c-sharp-number-of-days-in-a-month-using-a-switch#24996339)...
This is clearly an academic exercise that wants you to learn about the switch statement.
Here is a complete example that demonstrates a couple ways to do switch statements. Since you already grabbed the month number from the user you can switch on that value by creating a mapping between the month and the number of days in the month.
To wit:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine()); // WARNING: throws exception for non-integer input
Console.WriteLine(GetMonthName(monthInteger));
Console.WriteLine();
Console.Write("Display days in month (y/n)? ");
if (Console.ReadLine() == "y")
{
int daysInMonth = GetDaysInMonth_NoLeapYear(monthInteger);
if (daysInMonth > 0)
{
Console.WriteLine(String.Format("{0} days in {1}",
daysInMonth.ToString(),
GetMonthName(monthInteger)));
}
else
{
Console.WriteLine("Invalid month entered.");
}
Console.WriteLine();
}
Console.WriteLine("Hit enter to close");
Console.ReadLine();
}
private static String GetMonthName(int monthInteger)
{
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
String monthName = newDate.ToString("MMMM");
return monthName;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear(int monthInteger)
{
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 1: // jan
daysInMonth = 30;
break;
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
daysInMonth = 31;
break;
case 4: // apr
daysInMonth = 30;
break;
case 5: // may
daysInMonth = 31;
break;
case 6: // jun
daysInMonth = 30;
break;
case 7: // jul
daysInMonth = 31;
break;
case 8: // aug
daysInMonth = 31;
break;
case 9: // sep
daysInMonth = 30;
break;
case 10: // oct
daysInMonth = 31;
break;
case 11: // nov
daysInMonth = 30;
break;
case 12: // dec
daysInMonth = 31;
break;
}
return daysInMonth;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear_Compact(int monthInteger)
{
// uses case statement fall-through to avoid repeating yourself
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
case 5: // may
case 7: // jul
case 8: // aug
case 10: // oct
case 12: // dec
daysInMonth = 31;
break;
case 1: // jan
case 4: // apr
case 6: // jun
case 9: // sep
case 11: // nov
daysInMonth = 30;
break;
}
return daysInMonth;
}
}
GetDaysInMonth_NoLeapYear_Compact is included only to illustrate the case fall-through behavior that lets multiple case statements go to the same code.

Having trouble with code to convert number into a month

here is my source code, everything is good until i get to the output and I cant get this to work. Visual Studio doesn't like what I have in the output section, labeled //OUTPUT.
What do I need to add or change to get this to work?
static void Main(string[] args)
{
int monthNumber;
string monthName;
//INPUT
Console.WriteLine("Please enter the number of the month");
monthNumber = Convert.ToInt16(Console.ReadLine());
//PROCCESSESS
if (monthNumber == 1)
{
monthName = "January";
}
else if (monthNumber == 2)
{
monthName = "February";
}
else if (monthNumber == 3)
{
monthName = "March";
}
else if (monthNumber == 4)
{
monthName = "April";
}
else if (monthNumber == 5)
{
monthName = "May";
}
else if (monthNumber == 6)
{
monthName = "June";
}
else if (monthNumber == 7)
{
monthName = "July";
}
else if (monthNumber == 8)
{
monthName = "August";
}
else if (monthNumber == 9)
{
monthName = "September";
}
else if (monthNumber == 10)
{
monthName = "October";
}
else if (monthNumber == 11)
{
monthName = "November";
}
else if (monthNumber == 12)
{
monthName = "December";
}
//space to increase readability
Console.WriteLine(Environment.NewLine);
//OUTPUT
Console.WriteLine("Month:" + monthName);
Console.ReadLine();
}
monthName must be initialized before use. So you can change the declaration line as
string monthName = null;
That's because the code does not guarantee that monthName gets assigned. For example what if the input number is 13?
You have a lot of else if, but in the end, there's no else to cover the case where none of the if apply. Therefore the compiler can't guarantee that monthName was ever assigned. Maybe the user typed "28"?
It would look better to use a switch statement with twelve case sections and one default section.
But also, the month names are built into the framework. So with using System.Globalization; you could simply say
monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNumber);
or
monthName = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(monthNumber);
You can also get a DateTime directly from the input:
DateTime dateTime = DateTime.ParseExact(Console.ReadLine(), "%M", null);
Then
monthName = dateTime.ToString("MMMM");
a) declare a variable
b) if you are using month names, and you want some specific names, try using enum. really eazy and functional.
You can make your own setup of names/markings with your own pace of numbering those names/markings.
For Eg.
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Month in c# using DateTime

I am wondering if there is way to have the user enter a number like 01 and have that string converted to the month using dateTime. I know how to have the user enter a string such as 01/01/2011 and have the converted to a DateTime. Is there a way to use datetime to convert a two number string into a month. Something like this, but that would work
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
dt = Convert.ToDateTime(date).Month;
You could probably get it jumping through some hoops with DateTime, however;
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int monthNumber);
is probably easier.
It is already built into the .NET framework: see System.Globalization.DateTimeFormatInfo.MonthNames
It'd be easier to just have an array of 12 elements, each being a month.
String[] Months = new String[] {"Jan", "Feb"}; //put all months in
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
int index = 0;
if (!int.TryParse(date, out index)) {
// handle error for input not being an int
}
dt = Months[index];
If you really wanted to stick with using the DateTime class, you could take in the month and then tag on some day and year and use the method you provided in your code. For example...
dt = Convert.ToDateTime(date + "/01/2012").Month;
But this is less advised.
Your example is not complete, cause you need to specify which year and which day in the date.
Assuming that that data have to be of the current date, you can do something like this:
DateTime dt = new DateTime(DateTime.Now.Year, int.Parse("01"), DateTime.Now.Day);
Don't forget, obviously, add a couple of controls, like
Month range {1-12}
Month string is a number
EDIT
int month =-1;
if(int.TryParse(userInputString, out month)){
if(month>=1 && month <=12) {
DateTime dt = new DateTime(
DateTime.Now.Year,
month,
DateTime.Now.Day);
}
}
Hope this helps.
public static string ReturnMonthName(string pMonth)
{
switch (pMonth)
{
case "01" :
return "January";
case "02":
return "February";
case "03":
return "March";
case "04":
return "April";
case "05":
return "May";
case "06":
return "June";
case "07":
return "July";
case "08":
return "August";
case "09":
return "September";
case "10":
return "October";
case "11":
return "November";
case "12":
return "December";
default:
return "Invalid month";
}
Strip the month from your datetime and use a switch/case select to assign your variable.
switch (val)
{
case 1:
MessageBox.Show("The day is - Sunday");
break;
case 2:
MessageBox.Show("The day is - Monday");
break;
case 3:
MessageBox.Show("The day is - Tuesday");
break;
case 4:
MessageBox.Show("The day is - wednesday");
break;
case 5:
MessageBox.Show("The day is - Thursday");
break;
case 6:
MessageBox.Show("The day is - Friday");
break;
case 7:
MessageBox.Show("The day is - Saturday");
break;
default:
MessageBox.Show("Out of range !!");
break;
}

A less ugly way to localize DayOfWeek? [duplicate]

This question already has answers here:
C# Cultures: Localize DayOfWeek?
(2 answers)
Closed 9 years ago.
using System;
namespace Server.Custom.Extensions
{
public static class FriendlyExtensions
{
public static string Friendly(this DayOfWeek day)
{
if (day == DateTime.Now.DayOfWeek)
return "Hoy";
int dayOfWeek = (int)DateTime.Now.DayOfWeek;
int dayOfEvent = (int)day;
if (dayOfWeek + 1 == dayOfEvent || (dayOfWeek == 6 && dayOfEvent == 0))
return "MaƱana";
switch (day)
{
default:
case DayOfWeek.Monday: return "Lunes";
case DayOfWeek.Tuesday: return "Martes";
case DayOfWeek.Wednesday: return "Miercoles";
case DayOfWeek.Thursday: return "Jueves";
case DayOfWeek.Friday: return "Viernes";
case DayOfWeek.Saturday: return "Sabado";
case DayOfWeek.Sunday: return "Domingo";
}
}
}
}
Is there some way to localize this with Cultures? how? :(
By the way I want it to say "Today" or "Tomomorrow" too, not just convert the days
DateTime.Now.ToString("ddd", new CultureInfo("es-ES"));
or
DateTime.Now.ToString("dddd", new CultureInfo("es-ES"));
References:
DateTime.ToString Method (String)
How to: Extract the Day of the Week from a Specific Date
This code from here (see bottom) might put you on the right track.
CultureInfo german = new CultureInfo("de-DE");
DateTimeFormatInfo dtfi = german.DateTimeFormat;
Console.WriteLine("Days of the week for the {0} culture:",
german.Name);
for (int ctr = 0; ctr < dtfi.DayNames.Length; ctr++)
Console.WriteLine(" {0,-12}{1}", dtfi.DayNames[ctr],
dtfi.DayNames[ctr] == dtfi.DayNames[(int)dtfi.FirstDayOfWeek] ?
"(First Day of Week)" : "");

Categories