User friendly date input - c#

I have to code program, which will asks user about some data and then will print some text with this data.
Below is just piece of code (which works), there are others variables too.
class Student
{
static public DateTime birthDay;
public void GetStudentInformation()
{
Console.WriteLine("Enter student's birth date (as mm/dd/yyyy): ");
birthDay = DateTime.Parse(Console.ReadLine());
}
public void PrintStudentData(ref DateTime birthDay)
{
Console.WriteLine("Student was born in {0}", birthDay.ToString("d"));
}
}
class Program
{
static void Main(string[] args)
{
Student newStudent = new Student();
newStudent.GetStudentInformation();
newStudent.PrintStudentData(ref Student.birthDay);
Console.ReadKey()
}
}
When I'm asking about birthday I need only date, not exactly time.
There are questions:
How to change that input date by user would be in other format than mm/dd/yyyy?
How I would operate on output format date? So it wouldn't be yyyy-dd-mm but dd/mm/yyyy or dd.mm.yyyy?
I want to add I'm really beginner in C# and tried some code with CultureInfo, ParseExact, TryParse, and modyfing output string with {0:'dd/mm/yyyy'}.

Sounds like DateTime.TryParseExact is a good way to do it.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format, culture-specific
format information, and style. The format of the string representation
must match the specified format exactly. The method returns a value
that indicates whether the conversion succeeded.
DateTime birthDay;
if(DateTime.TryParseExact(Console.ReadLine(), "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out birthDay)
{
// Your input string can (and will) be parsed with MM/dd/yyyy format.
}
else
{
// Invalid format or value.
}
By the way, I changed your mm to MM because mm specifier is for minutes but MM specifier is for months.
For your questions;
How to change that input date by user would be in other format than
mm/dd/yyy?
You can't. This might create a lot of ambiguous situations like what is the format of 01/02/2016? Is it dd/MM/yyyy or MM/dd/yyyy? This totally depends on where you live and which culture settings you use.
How I would operate on output format date? So it wouldn't be
yyyy-dd-mm but dd/mm/yyyy or dd.mm.yyyy?
With output, if you mean the Console.WriteLine part, this The "d" standard format specifier uses ShortDatePattern of your CurrentCulture settings where you run this code. That means the output format depends on the current culture settings. If this property has dd/MM/yyyy, you will be fine. If it is not, you should format it with customd date format specifiers like;
Console.WriteLine("Student was born in {0}",
birthDay.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));

This let user input in format day/month/year and output as dd.MM.yyyy
static void Main()
{
Student newStudent = new Student();
newStudent.GetStudentInformation();
newStudent.PrintStudentData(ref Student.birthDay);
Console.ReadKey();
logEnd();
}
class Student
{
static public DateTime birthDay;
public void GetStudentInformation()
{
Console.WriteLine("Enter student's birth date as day/month/year");
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};
while (!DateTime.TryParseExact(Console.ReadLine(), formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out birthDay))
{
Console.WriteLine("Your input is incorrect. Please input again.");
}
// User input correct, birthDay can now be used
}
public void PrintStudentData(ref DateTime birthDay)
{
Console.WriteLine("Student was born in {0}", birthDay.ToString("dd.MM.yyyy"));
}
}

Related

Regarding DateTime Format "%h:%m:%s" allowing hour as "00"

I have a TextBox to enter time in the format "%h:%m:%s".
The allowed time inputs:
01:20:00
12:20:00
I am converting the string taken from TextBox using:
DateTime.TryParseExact("00:20:00", "%h:%m:%s",
culture, DateTimeStyles.None, out newData);
But above code converts hour 00 to 12 when providing the data through newData. I want to throw error in this case. Please provide your inputs.
It seems that you should try to parse to a TimeSpan instead of DateTime.
Use the following string.Format pattern to convert to a TimeSpan:
var pattern = #"hh\:mm\:ss";
see MSDN for more details: http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx
UPDATED
Working Sample code:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DateTime newData;
TimeSpan newSpan;
DateTime.TryParseExact("00:20:00", "%h:%m:%s",
CultureInfo.DefaultThreadCurrentCulture, DateTimeStyles.None, out newData);
Console.WriteLine(newData);
// 8/5/2014 12:20:00 AM
TimeSpan.TryParseExact("00:20:00", #"hh\:mm\:ss",
CultureInfo.DefaultThreadCurrentCulture, TimeSpanStyles.None, out newSpan);
Console.WriteLine(newSpan);
// 00:20:00
Console.WriteLine(newSpan.Hours);
// 0
Console.WriteLine(newSpan.TotalHours);
// 0.33~
Console.ReadLine();
}
}
}
You should be using upper-case "H" for 24-hour time.

Split string to convert to datetime causes an error

I try to convert persian date to standard datetime .The persian date has a format like this :1392/01/23.
My function :
public DateTime ConvertPeersianToEnglish(string persianDate)
{
string[] formats = { "yyyy/MMMM/dd" };
DateTime d1 = DateTime.ParseExact(persianDate, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
return d1;
}
So when i call this function and pass my persian date to it i got an error :
String was not recognized as a valid DateTime.
Why ?
Best regards
Use MM instead of MMMM:
string[] formats = { "yyyy/MM/dd" };
MM is month number 01 to 12
MMMM is full month name january to december (strings depend on culture).
Check out MSDN: Custom date and time format strings

DateTime Format - Getting System.FormatException in c#

I am very new to C#.. I am writing an appointment schedule program where in I want to provide Date and Time value as a string from console and then I want to parse it to DateTime format. But by doing so I am getting
"System.FormatException" - string was not recognized as a valid datetime
Here is my piece of code,
string Format = "dd/MM/yyyy hh:mm tt";
Console.WriteLine("Enter the appointment date and time in(dd/MM/yyyy hh:mm AM/PM) format");
User_Input = Console.ReadLine();
Date_Time = DateTime.ParseExact(User_Input,Format,CultureInfo.InvariantCulture);
When I provide input exactly as format i.e like 23/11/2012 08:30 pm.. I am getting the said exception. I want to output datetime with AM/PM. What have I done wrong?
The question is a little bit odd since your format string works with your given input string(in all cultures) and you want to output with the same format. Perhaps somebody entered 23/11/2012 18:30 pm instead which does not work with the AM/PM designator.
string format = "dd/MM/yyyy hh:mm tt";
DateTime dateTime = DateTime.ParseExact("23/11/2012 08:30 pm", format, CultureInfo.InvariantCulture);
string output = dateTime.ToString(format, CultureInfo.InvariantCulture);
outputs: 23/11/2012 08:30 PM
demonstration
Note that you can always use DateTime.TryParseExact to validate user input.

Parse a string to a date without slashes

In C# / Winform, I'm able to parse a string to a date if the user input: dd/mm/yyyy
DateTime.Parse(date).ToString();
I would like to be able to parse without the slash (like in a datagridview or a DateTimePicker for example).
01022012 should be parsed to 01/02/2012
Anyone know how to parse it with DateTime.Parse?
Here is my code :
private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
{
string date = Convert.ToString(e.FormattedValue).Trim();
if (date.Length > 0)
{
try
{
DateTime _date;
DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
date = _date.ToShortDateString();
dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
}
catch
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
}
Here is the Exception Message :
It says that : "System.FormatException: The string is not recognized as a DateTime valide"
Try with something like this...
string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, date);
... and, with date variable, you only need to...
string slashedValue = date.ToString("dd/MM/yyyy");
HuorSwords isn't wrong (other than the use of string as the input value), but the answer doesn't strictly answer the question: in order to display the date as requested, you need to format to a string after the fact:
DateTime date = DateTime.ParseExact(input,
"ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");
That seems like an awful lot of work when you could do something as simple as the two examples below. Date and time can be formatted using predefined formats and also user-defined formats.
This is a link to a brief video demonstrating both uses from a text editing program I'm designing.
https://od.lk/s/MTRfMjY2NzQxODVf/2022-03-20-20-55-52.mp4
This link will certainly get you on the right track:
https://www.vbtutor.net/vb2008/vb2008_lesson16.html
'Declaration (If you wish to use SpeechSynthesizer)
Private Ethro As SpeechSynthesizer = New SpeechSynthesizer()
Ethro.SpeakAsync(Format(Now, "Long Date"))
'Or a simple MsgBox:
MsgBox(Format(Now, "Long Date"))

DateTime.TryParseExact CultureInfo.InvariantCulture

Can anyone see what I'm doing wrong, I'm trying to parse the date to ensure its a valid date, if so convert it to the format I require.
I have tried different ways of doing this, but all return 01/01/0001 00:00:00.
value of string parseArrivalDate = 02/02/2013
DateTime ukDateFormat;
string ukFormat = "0:ddd, MMM d, yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
-------------------------------------EDIT-------------------------------
OK sorry, I did not explain it very well. If I enter UK format say 27/02/2013, and when I had UK format as dd/MM/yyyy it worked ok, problem was when I was entering US or any other format, it was returning the incorrect date, so I was changing the format round thinking that was the problem.
It has now dawned on me after reading your comments, that I had the uk format correct 1st time, so my problem is, how can I change the code, so that any date format can be parsed correctly.
Hope that makes more sense
Thanks
Your string
"0:ddd, MMM d, yyyy"
has a number 0, a colon :, and a format corresponding to
"Wed, Mar 27, 2013"
for example, if the culture is "en-GB" ("English (United Kingdom)"). It probably comes from a String.Format, Console.WriteLine or similar method call, where it is put into braces {} to format a text, as in
Console.WriteLine("The date {0:ddd, MMM d, yyyy} was selected.", someDateTime);
It would work with code like:
string arrivalDateString = "Wed, Mar 27, 2013";
...
DateTime result;
string yourFormat = "ddd, MMM d, yyyy"; // no "0:" part
bool isOK = DateTime.TryParseExact(arrivalDateString, yourFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (isOK)
{
// Worked! Answer is in 'result' variable
}
else
{
// Didn't work! 'result' variable holds midnight 1 January 0001
}
The format that corresponds to "27/03/2013" is "dd/MM/yyyy" (or "d/M/yyyy"). The format that corresponds to "03/27/2013" is "MM/dd/yyyy" (or "M/d/yyyy").
It is not possible to have one method that handles both styles of dates, since a string like
"01/04/2013" /* ambiguous */
could mean either
1 April 2013
January 4, 2013
so it's ambiguous, and there's no way we can tell what date is meant. See also Wikipedia: Calendar date → Date format.
your date string is: 02/02/2013 and the format you are using is "0:ddd, MMM d, yyyy" which is wrong, it should be MM/dd/yyyy if its month first.
DateTime ukDateFormat;
string ukFormat = "MM/dd/yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat,CultureInfo.InvariantCulture,DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
If the date you have specified contains day first then month, then use the format "dd/MM/yyyy", By the way you can using single d and M for both single digit and double digits day/month.
Currently you are getting the DateTime.MinValue, since parsing is failing because of the invalid format.
I have no idea what you expect, but your input string does not met your ukFormat pattern! So it's totally right behavior.
Change your pattern to ""dd/MM/yyyy"" to make TryParseExact work.
Your provided format looks a little strange. Try to replace it with this
string ukFormat = "dd/MM/yyyy";
And read the documentation on this.
Thanks everyone for helping me understand where I was going wrong, the code below is what I have came up with although not perfect as 03/06/2013 UK is different than the meaning of 03/06/2013 US.
I have added text above the text box asking people to use format dd/mm/yyyy.
string getArrivalDate = ArrivalDate;
string getDepartureDate = DepartureDate;
string dteFormat = "dd/MM/yyyy";
DateTime result;
string arrivalDateParse;
string departureDateParse;
bool arrival = DateTime.TryParseExact(getArrivalDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (arrival)
{
arrivalDateParse = getArrivalDate;
}
else
{
arrivalDateParse = "notvalid";
}
bool depart = DateTime.TryParseExact(getDepartureDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (depart)
{
departureDateParse = getDepartureDate;
}
else
{
departureDateParse = "notvalid";
}
if (arrivalDateParse == "notvalid" || departureDateParse == "notvalid")
{
if (Request.IsAjaxRequest())
{
return Json(new { Confirm = "Date not in correct format" }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Error"] = "Sorry your arrival date or departure date is not a valid format, please enter date as dd/mm/yyyy example 02/12/2013";
return View("~/Views/Shared/Error.cshtml");
}
If anyone can improve on the code, it would be appreciated.
Thanks
George
Rather than using InvariantCulture for this consider using RoundTrip style (ISO-8601). See this MSDN article: http://msdn.microsoft.com/en-us/library/bb882584.aspx

Categories