I am working on a calendar. And here I want to check if the users input is a date and if it's not showing an error. I heard about DateTime.TryParse. How can I use this here properly? Can maybe anyone explain it in simple words?
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
}
Use DateTime.TryParseExact in this way:
public void addMeeting()
{
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
Console.WriteLine("Add a schedule for specific dates: ");
string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;
bool validDate = DateTime.TryParseExact(
readAddMeeting,
dateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out scheduleDate);
if(validDate)
Console.WriteLine("That's a valid schedule-date: {0}", scheduleDate.ToShortDateString());
else
Console.WriteLine("Not a valid date: {0}", readAddMeeting);
}
The method returns a bool indicating whether it could be parsed or not and you pass a DateTime variable as out parameter which will be initialized if the date was valid.
Note that i'm using DateTimeFormatInfo.InvariantInfo because you don't want to use the local DateTime format but one that works in any culture. Otherwise the / in dd/MM/yyyy would be replaced with your current culture's date separators. Read
Even if it sounds a bit brutal, but it seems ike you should do some readup on arrays/lists, foreach loops and DateTime.TryParse.
That aside you have different possible date formats and want to see if one of them is valid. If we take the example from the msdn homepage for tryparse https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx and use foreach it becomes quite easy:
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
bool isDateOk = false;
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
foreach (string myDateFormat in dateFormats)
{
DateTime dateValue;
if (DateTime.TryParse(readAddMeeting, dateValue))
{
isDateOk = true;
}
}
if (isDateOk == false)
{
Console.Writeline("Sorry this is not a valid date");
}
}
Related
I am reading an input from a device on a comm port, that is a date in the following format "dd/MM/yyyy hh:mm" to a string value. I am trying to format the date to show "ddMMyyyy hh:mm:ss". I have tried the following but get the error below code:
(input value is "31/08/2018 02:32")
public string ParseLine(string Line)
{
var input = Line.Split(',');
var dateTime = DateTime.Parse (input[0]);
var Action = input[1] == "1" ? "ONL" : "OFL";
var readerAddr = input[1] == "1" ? "S" : "T";
var TagType = input[2];
var TagNum = input[3].Substring(TagType.Length);
return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy hh:mm:ss}";
}
Any advise will be appreciated?
Use DateTime.TryParseExact to check if 'input[0]' has a valid datetime value. Example:
public string ParseLine(string Line)
{
...
if(!DateTime.TryParseExact(input[0], "ddMMyyyy hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out var result))
{
//Is not a valid date :C
}
Console.WriteLine("Valid date: " + result);
}
In case date time would be in some weird format, you will need to use DateTime.ParseExact(..) method like this:
var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy hh:mm");
However, your format is one of the accepted ISO formats, so it should work like you wrote down. The best reason why is does not work is that the value of input[0] is not what you expect, so at first check what this variable actually contains.
Thanks to everyone's comments and advise I managed to get it right by using these two methods:
var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
and
return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy HH:mm:ss}";
I have a TextBox in which the user can type a date. I only expect following formats:
12.12.2017
12.02.2017
12.2.2017
02.12.2017
2.12.2017
02.02.2017
2.2.2017
So there can be a leading zero or not.
I am currently parsing the DateTime with following code:
DateTime myDate = new DateTime();
bool success = DateTime.TryParseExact(TboDate.Text, "dd.MM.yyyy",
CultureInfo.CurrentUICulture, DateTimeStyles.None, out myDate);
Dates like 12.2.2017 can not be parsed successfully with that code. But I don't want to check the string everytime and parse it then with the matching format d.M.yyyy, dd.M.yyyy, d.MM.yyyy and so on. Is there an easier way to tell the method, that there can be leading zeros?
They could all be parsed without a problem with Parse/TryParse f.e. with de-DE culture:
var dates = new[] { "12.12.2017", "12.02.2017", "12.2.2017", "02.12.2017", "2.12.2017", "02.02.2017", "2.2.2017" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParse(dateStr, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
But you could also use ParseExact if you specify all allowed formats:
string[] allowedFormats = { "dd.MM.yyyy", "d.MM.yyyy", "dd.M.yyyy", "d.M.yyyy" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParseExact(dateStr, allowedFormats, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
Update
As Jon Skeet has mentioned it's not necessary to specify multiple, this handles all: "d.M.yyyy"
I have a set of array.
//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"]
I have an array of strings, among these strings there is one string which is in date format.
I need to do a foreach and need to check which string is in the date format.
If we got the date string "2016-08-30T18:30:00.000Z" I need to convert it to basic date format but in correct timezone, here the date is 2016-08-31 but what I need as out put is
["vishnu","31/8/2016","1992","banglore"]
not
//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]
the aim is from the array, if string is in date string format, convert it.
public static void Main(string[] args)
{
string inputString = "2016-08-31T18:30:00.000Z";
DateTime enteredDate = DateTime.Parse(inputString);
Console.WriteLine(enteredDate);
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime dtx = enteredDate.ToLocalTime();
String.Format("{0:d/MM/yyyy}", dDate);
Console.WriteLine(dtx);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
// DateTime dt = convertedDate.ToLocalTime();
}
If you need to correct the DateTime for the time zone, you can use TimezoneInfo.ConvertTime():
string inputString = "2016-08-31T18:30:00.000Z";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);
// write this here back into the array using your format
Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
For further reference check out this post. This answer is inspired by it to use TimeZoneInfo.
DateTime dDate;
do this operation iside foreach
if (DateTime.TryParse(answerString, out dDate))
{
DateTime enteredDate = DateTime.Parse(answerString);
var Date = enteredDate.ToString("dd/MM/yyyy");
answerString = Date;
Console.WriteLine(answerString);
}
else{
//operation
}
thanks to mong zhu
Try using DateTimeOffset rather than DateTime as it is built to handle time zones.
Here's the code:
string inputString = "2016-08-31T18:30:00.000Z";
DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);
DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);
This produces the following for me in GMT+09:30:
2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30
To get it in Indian time try this:
DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);
I get 2016/09/01 00:00:00 +05:30 now.
I know i could do this and it works
string Dob; //string
Console.WriteLine("Enter date of Birth in format DD/MM/YYYY: ");
Dob = Console.ReadLine();
But i want something like this! a predefined method or shorthad way
DateTime Dob; //DateTime
Console.WriteLine("Enter date of Birth in format DD/MM/YYYY: ");
//What i am expecting, but is not possible as its DateTime
Dob = Console.ReadLine(); // expects a string
Is there a specific method to get date only into the Dob Variable directly from the Key Board.
Is there a predefined method for this in the DateTime class?
What's the best way or shortest way to achieve this?
string line = Console.ReadLine();
DateTime dt;
while (!DateTime.TryParseExact(line, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out dt))
{
Console.WriteLine("Invalid date, please retry");
line = Console.ReadLine();
}
You can extend the string class in .net by writing an extension function as the following.
public static class Extensions
{
public static DateTime? Dob(this string strLine)
{
DateTime result;
if(DateTime.TryParseExact(strLine, "dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal,out result))
{
return result;
}
else
{
return null;
}
}
}
You can then use it on any string object. See the example below to see what I'm talking about.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter your date of birth in DD/MM/YYYY:");
// Option 1.
// The Console.ReadLine() function returns a string.
string strDob = Console.ReadLine();
DateTime? dob1 = strDob.Dob();
// Option 2.
// You can combine the two steps together into one line for smoother reading.
DateTime? dob = Console.ReadLine().Dob();
}
}
Note: The question mark (?) at the end of the DateTime type converts the DateTime "struct" into a nullable "object". If you set a DateTime "struct" equal to null it will throw an exception where as DateTime? can be set to null. It is good practice to consider using DateTime? (nullable) as opposed to using the DateTime "struct"
This method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime myDate = DateTime.ParseExact("2009/05/08","yyyy/MM/dd",
System.Globalization.CultureInfo.InvariantCulture)
So far, this is the easiest and shortest way i found, as cubrr commented.
DateTime Dob;
Console.WriteLine("Enter date of Birth in format MM/DD/YYYY: ");
//accepts date in MM/dd/yyyy format
Dob = DateTime.Parse(Console.ReadLine());
I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}