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;
}
Related
I have for some time been working on a console calendar that counts on its own to a certain date with the correct day of week, date etc, which then allows you to insert data on that day. All that is done, but now I'm adding a function where you can put the dates from start date to end date into a text file. The output will be something like:
05.06.2016 Tuesday
06.06.2016 Wednesday
07.06.2016 Thursday
01.06.2016 Friday
02.06.2016 Saturday
03.01.2016 Sunday
04.01.2016 Monday
05.01.2016 Tuesday
06.01.2016 Wednesday
07.01.2016 Thursday
01.01.2016 Friday
02.01.2016 Saturday
This sent me off to this MainInputSection class of my program, and I had to add parameter so that I could alter the messages from just "Input YEAR" etc to "Input start of YEAR for file" etc.
There are now three switches right next to each other that does almost the same thing, and this section of my program therefore felt a bit simple, repetetive, and hard-coded.
What I'd like is a loop or something that shortens this stuff and makes it less nooby the way it is now in order to get the right Console.WriteLine(); matched with the correct Console.ReadLine(); to fill in the int[] arrayAnswers = { answerYear, answerMonth, answerDay }; correcly, but more professionally. I'm thinking something like a for each loop or something, but I only halfway see a solution like that and I need help.
public class MainInputSection
{
public static int[] GetUserInputDate(string mode)
{
int answerYear;
int answerMonth;
int answerDay;
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calender":
Console.WriteLine("Input YEAR");
break;
case "fileStart":
Console.WriteLine("Input start of YEAR for file");
break;
case "fileEnd":
Console.WriteLine("Input end of YEAR for file");
break;
}
Console.ResetColor();
answerYear = Convert.ToInt32(Console.ReadLine());
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calendar":
Console.WriteLine("Input MONTH");
break;
case "fileStart":
Console.WriteLine("Input start of MONTH for file");
break;
case "fileEnd":
Console.WriteLine("Input end of MONTH for file");
break;
}
Console.ResetColor();
answerMonth = Convert.ToInt32(Console.ReadLine());
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calendar":
Console.WriteLine("Input DAY");
break;
case "fileStart":
Console.WriteLine("Input start of DAY for file");
break;
case "fileEnd":
Console.WriteLine("Input end of DAY for file");
break;
}
Console.ResetColor();
answerDay = Convert.ToInt32(Console.ReadLine());
int[] arrayAnswers = { answerYear, answerMonth, answerDay };
return arrayAnswers;
}
}
So what you have to do is, group the common things together inside a method, here all cases should display some text in the console with a color and then call the reset color option, and store the user input to an integer variable. So group them together inside a method and return the integer value from the method. I think the signature of the method should be like the following:
public static int GetInput(string displayMessage)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(displayMessage);
Console.ResetColor();
return int.Parse(Console.ReadLine());
}
And you can use the method like the following:
public static int[] GetUserInputDate(string mode)
{
int answerYear = 0;
int answerMonth = 0;
int answerDay = 0;
switch (mode)
{
case "calender":
answerYear = GetInput("Input YEAR");
answerMonth = GetInput("Input MONTH");
answerDay = GetInput("Input DAY");
break;
case "fileStart":
answerYear = GetInput("Input start of YEAR for file");
answerMonth = GetInput("Input start of MONTH for file");
answerDay = GetInput("Input start of DAY for file");
break;
case "fileEnd":
answerYear = GetInput("Input end of YEAR for file");
answerMonth = GetInput("Input end of MONTH for file");
answerDay = GetInput("Input end of DAY for file");
break;
}
int[] arrayAnswers = { answerYear, answerMonth, answerDay };
return arrayAnswers;
}
How do I convert a datetime field to a string with the format 1st Feb 2011 in C# ? doj is datetime field in sql server.
string DateOfJoin = dt.Rows[0]["DOJ"].ToString();//2011-02-01 00:00:00.000
First of all, 2/1/2011 can be 1st Feb or 2nd Jan not 1st Jan.
Second, let's parse your string to DateTime.
DateTime dt = DateTime.ParseExact(dt.Rows[0]["DOJ"].ToString(),
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
or you can explicitly cast it to DateTime
DateTime dt = (DateTime)dt.Rows[0]["DOJ"];
Third, .NET does not have a built-in way in BCL to generate day suffix. But Lazlow write a method for that which works seems okey to me as;
static string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
and you can this method like;
string DateOfJoin = String.Format("{0}{1} {2}",
dt.Day,
GetDaySuffix(dt.Day),
dt.ToString("MMM yyyy", CultureInfo.InvariantCulture));
which generates
use format below to get the similar without suffix see explanation
string DateOfJoin = dt.Rows[0]["DOJ"].ToString("dd MMMM yyyy");
However to get the suffix you'll need to break it up so that you get the day separate i.e.
string DateOfJoin = dt.Rows[0]["DOJ"].ToString("dd MMMM yyyy");
I would use below if you really need the suffix
string day = dt.Rows[0]["DOJ"].ToString("dd");
day = GetDaySuffix(Int32.Parse(day));
This using a function to add the suffix that I originally found here
string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
string DateOfJoin = String.Format("{0} {1}", day, dt.Rows[0]["DOJ"].ToString("MMMM yyyy"));
Not tested but should be useful start
Var dt = DateTime.Parse(DateOfJoin);
dt.ToString('F');
See bottom of the following page for more formats
Msdn DateTime
Depending on the specified culture, long date strings can be achieved by casting the object to DateTime and then calling ToString() with the format parameter.
string DateOfJoin = ((DateTime)dt.Rows[0]["DOJ"]).ToString("D");
Further reference here
Edit: Formatting with things like '1st', '2nd', requires you to write a custom method which evaluates the day number and appends the correct string to it, something like:
private string GetSuffix(DateTime dt)
{
if(dt.Days % 10 == 1)
{
return dt.Days.ToString() + "st";
}
else if(dt.Days % 10 == 2)
{
return dt.Days.ToString() + "nd";
}
else if(dt.Days % 10 == 3)
{
return dt.Days.ToString() + "rd";
}
else
{
return dt.Days.ToString() + "th";
}
}
And then add this part of the string, to a ToString("Y") of the DateTime, like:
string DateOfJoin = GetSuffix((DateTime)dt.Rows[0]["DOJ"]) + " " + ((DateTime)dt.Rows[0]["DOJ"]).ToString("Y");
This tack can be accomplished with using the following approach:
DateTime date = new DateTime(2015, 01, 01);
// 1st Jan 2015
string s = Ordinal.Add(date.Day) + date.ToString(" MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
Here the Ordinal class is implemented as follows:
static class Ordinal {
public static string Add(int num) {
if(num <= 0) return num.ToString();
switch(num % 100) {
case 11:
case 12:
case 13:
return num + "th";
}
switch(num % 10) {
case 1: return num + "st";
case 2: return num + "nd";
case 3: return num + "rd";
default: return num + "th";
}
}
}
Try this
string DateOfJoin =Convert.ToDateTime( dt.Rows[0]["DOJ"]).ToString("dd MMMM yyyy HH:mm:ss");
string DateOfJoin =Convert.ToDateTime( dt.Rows[0]["DOJ"]).ToString("dd MMMM yyyy");
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.
int MM;
int DD;
int YYYY;
switch(MM)
{
case 1:
DD = 31;
break;
case 2:
DD = 28;
LDD = 29;
break;
case 3:
DD = 31;
break;
case 4:
DD = 30;
break;
case 5:
DD = 31;
break;
case 6:
DD = 30;
break;
case 7:
DD = 31;
break;
case 8:
DD = 31;
break;
case 9:
DD = 30;
break;
case 10:
DD = 31;
break;
case 11:
days = 30;
break;
case 12:
DD = 31;
break;
default:
{
Console.WriteLine("Invalid option");
}
}
if(Date == MM/DD/YYYY)
string Date = Console.ReadLine();
I am trying to write a code that would accept the date as string and only in this format mm/dd/yyyy and the time has to accepted only in this format 10:00AM
By using DateTime i am getting the time in this format 10:00:00, the hour,minute,second format which i don't want.
I dont want to use try catch, exception.
Use DateTime.ParseExact and write your format string following these guidlines:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You can use DateTime.ParseExact method and write your format definition in its second parameter.
I suggest DateTime.TryParseExact, this will check if the string is in the format you want, and return false if it isn't, and return true and populate your date if it is.
You should go with DateTime.TryParseExact, as this method doesn't throws an exception for invalid dates:
DateTime parsed;
var input = "08/03/2013 08:30AM";
if (DateTime.TryParseExact(input, "MM/dd/yyyy hh:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
Console.WriteLine("ok");
else
Console.WriteLine("not ok");
How does one go about finding the month name in C#? I don't want to write a huge switch statement or if statement on the month int. In VB.Net you can use MonthName(), but what about C#?
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
Use the "MMMM" format specifier:
string month = dateTime.ToString("MMMM");
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime
//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}