Date and Time Formatting in c# - c#

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

Related

How to convert datetime field to string like 1st Feb 2011?

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

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.

Why won't my c# application work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This program is supposed to get you a garfield comic from the date you entered or the daily comic. The first button should allow you to pick a custom comic but only the daily comic (button 2) seems to work Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Garfield_Comic_Viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int month = int.Parse(textBox1.Text);
int day = int.Parse(textBox2.Text);
int year = int.Parse(textBox3.Text);
switch (month)
{
case 1:
month = 01;
break;
case 2:
month = 02;
break;
case 3:
month = 03;
break;
case 4:
month = 04;
break;
case 5:
month = 05;
break;
case 6:
month = 06;
break;
case 7:
month = 07;
break;
case 8:
month = 08;
break;
case 9:
month = 09;
break;
}
switch (day)
{
case 1:
day = 01;
break;
case 2:
day = 02;
break;
case 3:
day = 03;
break;
case 4:
day = 04;
break;
case 5:
day = 05;
break;
case 6:
day = 06;
break;
case 7:
day = 07;
break;
case 8:
day = 08;
break;
case 9:
day = 09;
break;
}
pictureBox1.ImageLocation = ("http://garfield.com/uploads/strips/" +year+ "-" +month+ "-" + day + ".jpg");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string mon = DateTime.Now.ToString("MM");
string d = DateTime.Now.ToString("dd");
string y = DateTime.Now.ToString("yyyy");
pictureBox1.ImageLocation = "http://garfield.com/uploads/strips/" + y + "-" + mon + "-" + d + ".jpg";
DateTime whole = DateTime.Now;
}
}
}
The problem is you're expecting integers to behave like strings.
The point you're missing is that:
int a = 01;
is the same as:
int a = 1;
There's no difference. You can't pad an integer. What you need is to format the integers into a string, using a format specifier. Something like this:
pictureBox1.ImageLocation =
string.Format("http://garfield.com/uploads/strips/{0:D4}-{1:D2}-{2:D2}.jpg",
year, month, day);
This will give a string that contains the numbers in the format yyyy-mm-dd.
(The documentation for padding string-formatted integers is here.)

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

How to get the month name in C#?

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

Categories