A less ugly way to localize DayOfWeek? [duplicate] - c#

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)" : "");

Related

Condition base on Week of year (weekly changing method)

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();
}
}

How to get all weekends within a date range in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is there a simple way or framework to get all weekends within a date range in C#?
Is it possible to do with LINQ as well?
If you make a way to enumerate all days, you can use LINQ to filter to weekends:
IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
{
for (DateTime i = start; i < end; i = i.AddDays(1))
{
yield return i;
}
}
var weekends = GetDaysBetween(DateTime.Today, DateTime.Today.AddDays(365))
.Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);
I found how to do it.
http://www.dotnetjalps.com/2011/06/finding-saturdaysunday-between-date.html
namespace DatimeApplication
{
class Program
{
static void Main(string[] args)
{
DateTime startDate=new DateTime(2011,3,1);
DateTime endDate = DateTime.Now;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (var i = 0; i <= days; i++)
{
var testDate = startDate.AddDays(i);
switch (testDate.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine(testDate.ToShortDateString());
break;
}
}
Console.ReadLine();
}
}
}
That's not really difficult to code... Here's an efficient iterator:
public static IEnumerable<DateTime> GetWeekends(DateTime startDate, DateTime endDate)
{
startDate = startDate.Date;
endDate = endDate.Date;
if (endDate < startDate)
yield break;
var currentDate = startDate;
// Advance to next Saturday
switch (currentDate.DayOfWeek)
{
case DayOfWeek.Saturday:
break;
case DayOfWeek.Sunday:
yield return currentDate;
currentDate = currentDate.AddDays(6);
break;
default:
currentDate = currentDate.AddDays(DayOfWeek.Saturday - currentDate.DayOfWeek);
break;
}
while (currentDate <= endDate)
{
yield return currentDate;
currentDate = currentDate.AddDays(1);
if (currentDate <= endDate)
yield return currentDate;
currentDate = currentDate.AddDays(6);
}
}

How to find out number of installments between two dates? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose a Bank-Customer pays RD installments at every last day of the month.
So there must be 2 installments between the dates 12th October, 2013 and 10th December, 2013.
How can I find out how many installments the customer paid during this period of tine?
Should I use NodaTime library?
Ok. Here is my effort:
public sealed class DateDifference
{
int years;
public int Years
{
get { return years; }
}
int months;
public int Months
{
get { return months; }
}
int days;
public int Days
{
get { return days; }
}
public override string ToString()
{
return string.Format("[DateDifference Years={0}, Months={1}, Days={2}]", years, months, days);
}
public DateDifference(DateTime earlier, DateTime later)
{
if (later < earlier)
throw new ArgumentException("later is earlier than 'earlier'.");
bool isleapday = (earlier.Month == 2 && earlier.Day == 29);
DateTime tmp = isleapday ? new DateTime(earlier.Year, 2, 28) : earlier;
while (true)
{
try
{
tmp = tmp.AddYears(1);
if (isleapday && DateTime.IsLeapYear(tmp.Year))
tmp = new DateTime(tmp.Year, 2, 29);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
years++;
earlier = tmp;
}
else
{
break;
}
}
// Add months
tmp = earlier;
while (true)
{
try
{
tmp = tmp.AddMonths(1);
if (isleapday && tmp.Day != 29 && tmp.Month != 2)
tmp = new DateTime(tmp.Year, tmp.Month, 29);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
months++;
earlier = tmp;
}
else
{
break;
}
}
tmp = earlier;
while (true)
{
try
{
tmp = tmp.AddDays(1);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
days++;
earlier = tmp;
}
else
{
break;
}
}
}
DateDifference dateDifference = new DateDifference(startDateTextBox.Value, endDateTextBox.Value);
this.noOfInstallmentsTextBox.Text = ((int)++dateDifference.Months).ToString();
So I'll start off by saying I'm not prioritizing speed here. Datetime issues are tricky. Writing methods that you can be sure will work in all sorts of corner cases all over the world is hard. This approach is designed to work despite all edge cases and for that to be clear to the reader. It does not attempt to make cleaver optimizations because the tend to not work in odd edge cases, which are simply too common to ignore in the datetime world.
So first off we'll start with a simple helper method to get all of the days between two dates:
public static IEnumerable<DateTime> Days(DateTime start, DateTime end)
{
DateTime current = start;
while (current < end)
{
yield return current;
current = current.AddDays(1);
}
}
(If you want something more general purpose here you might get the next date after start, if you want all returned values to be "midnight". You might also swap start and end if they are in the reverse order, or throw an exception, etc. Also consider the exact semantics that you want; I have the bounds inclusive on start and exclusive on end, you may want it entirely inclusive, entirely exclusive, etc.)
We'll also create a method to determine if a date is the last day of the month.
public static bool IsLastDayOfMonth(DateTime date)
{
return date.AddDays(1).Month != date.Month;
}
We can actually define the last day of the month as being the only date for which its month is different from the following day's month.
Now when we combine these together we have an implementation that is very simple and clear to the reader:
public static int InstallmentCount(DateTime start, DateTime end)
{
return Days(start, end)
.Where(day => IsLastDayOfMonth(day))
.Count();
}
I hope it will help you.
int foo(DateTime start, DateTime end)
{
int count = end.Month - start.Month;
if (count < 0)
count += 12;
count += 12 * (end.Year - start.Year);
return count;
}

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;
}

Categories