How to parse date with minutes contains value 60? - c#

I am getting exception when the minute contains value 60
var date = "30/10/14 08:60";
var result = DateTime.ParseExact(date, "dd/MM/yy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None);
How do i parse it correctly??

Either pass a correct value(>=0 || <=59) or use this:
var date = "30/10/14 08:60";
DateTime dateResult;
bool canParse = DateTime.TryParseExact(date, "dd/MM/yy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateResult);
if (!canParse)
{
string datePart = date.Split().First();
DateTime dtOnly;
if (DateTime.TryParseExact(datePart, "dd/MM/yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dtOnly))
{
string timePart = date.Split().Last();
string hourPart = timePart.Split(':')[0];
string minutePart = timePart.Split(':').Last();
int hour, minute;
if (int.TryParse(hourPart, out hour) && int.TryParse(minutePart, out minute))
{
TimeSpan timeOfDay = TimeSpan.FromHours(hour) + TimeSpan.FromMinutes(minute);
dateResult = dtOnly + timeOfDay; // 10/30/2014 09:00:00
}
}
}

First of all, the data is invalid, and this is why an exception is raised.
So, basically there are 2 resolutions:
If the data is from the 3rd party, my suggestion is that after consulting with your boss or company's lawyers you/your company asks the 3rd party to provide valid data, since you don't have legal obligation to fix/tolerate the invalid data for the 3rd party. IMO, you shouldn't.
If the data is from your legacy internal systems, you/company should fix the bugs that may produce 60. If for some reasons the bugs can't be fixed shortly, you may write a parser for example using regular expression to parse the data and tolerate 60.
So the 2nd resolution with regular expression is to answer your question directly. However, please be mindful that "30/10/14 08:60" is invalid, and must be fixed sooner or later in the data source.
BTW, here's the link with some regular expressions you may try.

For international convention are 60 minutes in an hour.
The sixtieth minute would be 59, in fact if you count from 0 to 59 find that they are 60 numbers. The date you write 8:60 does not exist, the value of them is 9:00.
Try this(Obviously only date1 raises an exception):
var date = "30/10/14 8:59";
var date1 = "30/10/14 9:00";
var result = DateTime.ParseExact(date, "dd/MM/yy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None);
var result1 = DateTime.ParseExact(date1, "dd/MM/yy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None);
In addition at this you can use this for controlling a data and receiving a message true/false
var date = "30/10/14 08:60";
DateTime outData;
Boolean flagCorrectData = DateTime.TryParseExact(date, "dd/MM/yy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out outData);
if (flagCorrectData)
{
MessageBox.Show("Date correct");
}
else
{
MessageBox.Show("Date error");
}

If you always know if the time portion of your date string is of the format HH:mm, you can do this to get the right DateTime date:
string dateString = "30/10/14 08:60";
string[] dateParts = dateString.Split(' ');
DateTime date = DateTime.ParseExact(dateParts[0],"dd/MM/yy",CultureInfo.InvariantCulture);
string[] timeParts = dateParts[1].Split(':');
date=date.AddMinutes(double.Parse(timeParts[0])*60+double.Parse(timeParts[1]));

If you only care precisely about the special case of :60, you can use 60 in ParseExact explicitly:
string date = "30/10/14 08:60";
DateTime result;
if(DateTime.TryParseExact(date, "dd/MM/yy HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.None,out result))
{
return result;
}
//Handle weird :60
if(DateTime.TryParseExact(date, "dd/MM/yy HH:60",
CultureInfo.InvariantCulture, DateTimeStyles.None,out result))
{
return result.AddMinutes(60);
}
throw new ArgumentException("date");

Related

Use DateTime.TryParseExact to format date string and ignore time

I want to parse string date to DateTime but ignoring time.
My expected date format is M/d/yyyy which is 3/29/2018 (without leading zero).
The thing is string can be with or without time part and time can have different formats that I will not predict.
var inputDateString = "12/31/2017 12:00:00 AM" // false, but I want to parse
var inputDateString = "12/31/2017" // true
DateTime.TryParseExact(inputDateString, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate);
Is there any way to parse date string having only specific date format and ignore time?
There is an overload to TryParseExact that allows you to pass in multiple formats. If you know in advance which formats to expect, you can use this overload:
void Main()
{
string[] validFormats = {"M/d/yyyy", "M/d/yyyy hh:mm:ss tt"};
var inputDateString1 = "12/31/2017 12:00:00 AM"; // false, but I want to parse
var inputDateString2 = "12/31/2017"; // true
DateTime.TryParseExact(inputDateString1, validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt1);
DateTime.TryParseExact(inputDateString2, validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt2);
}
You can then get only the date portion using the Date property.
You could strip the time part from the input string, or parse the full input, using only the .Datepart.
var parsedDate = DateTime.MinValue;
var inputDateString = "12/31/2017 12:00:00 AM"; // false, but I want to parse
// option 1: use only the date part
if (DateTime.TryParseExact((inputDateString ?? "").Split(' ')[0] , "M/d/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
Console.WriteLine(parsedDate);
// option 2: use the full input, but ignore the time
if (DateTime.TryParseExact(inputDateString, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
Console.WriteLine(parsedDate.Date);
Personally, I would go with the first option.
If you always want to only parse the Date portion that can be done by explicitly ensuring the string is only 10 characters in length. This is a somewhat convoluted example but you can strip out what you don't need, you'll get the idea:
var inputDateString = "12/31/2017 12:00:00 AM";
string datePortion = string.Empty;
DateTime dt;
if (inputDateString.Length>10)
{
// take first 10 characters of inputDateString
datePortion = inputDateString.Substring(0, Math.Min(inputDateString.Length, 10));
}
else if (inputDateString.Length==10)
{
// inputDateString is already 10 characters
datePortion = inputDateString;
}
else
{
// inputDateString is less than 10 characters, no date found, do nothing.
}
if(!DateTime.TryParse(datePortion, out dt))
{
// handle error that occurred,
}
else
{
// parse was successful, carry on.
}

DateTime.ParseExact: String was not recognized as a valid DateTime

I am trying to get the date (& datetime) from the url and then convert it into its proper format before storing it in the db.
var reqDate = Request.QueryString["StartDate"];
//at this point I have reqDate: 05/15/2018 00:00:00
reqDate = reqDate.Substring(0, reqDate.IndexOf(" ") + 1);
//after stripping off the time part I have: 05/15/2018
timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
//but this throws the exception
URL:
Same is the case with startDateTime
var reqDateTime = Request.QueryString["startDateTime"];
timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
In your first scenario, No need to add +1 after reading indexOf(" "). +1 adding extra space to date
//Lets take date in string is "05/15/2018 00:00:00"
Console.WriteLine(s.Substring(0, reqDate.IndexOf(" ")+1)); /*This will print "05/15/2018 " WITH EXTRA SPACE*/
Correct way is s.Substring(0, s.IndexOf(" "))
In second scenario, use date format like HH:mm:ss instead of HH:mm tt
//Here use "hh:mm:ss" instead of "hh:mm tt"
DateTime dateTime = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Elegant approach would be:
#Credit Stephen Muecke
After looking at your URL, you can write a method having parameters like,
public ActionResult Create(int empId, int attID, DateTime startDate, DateTime startDateTime)
{
/*Do your work here, DefaultModelBinder will take care of parameters*/
}
First Example fix:
var reqDate = Request.QueryString["StartDate"];
reqDate = reqDate.Substring(0, reqDate.IndexOf(" "));
timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Second Example Fix:
var reqDateTime = Request.QueryString["startDateTime"];
timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

I am getting Error as String was not recognized as a valid DateTime

private string format = "dd/MM/yyyy HH:mm:ss";
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format, CultureInfo.InvariantCulture);
I am getting error when executing this line string was not recognized as a Valid Date Time.
I have tried this also but it not works
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format,null);
Your format string must be "d/M/yyyy", take a look at this.
Basically
MM : The month, from 01 through 12.
while
M : The month, from 1 through 12.
The same for the day part.
You are telling DateTime.ParseExact that you are expecting a string with format dd/MM/yyyy HH:mm:ss but you are giving it a string with format d/M/yyyy.
You need to change your format to just d/M/yyyy.
Also I suggest using DateTime.TryParseExact to verify the validity of your string instead of using exceptions.
var okay = DateTime.TryParseExact(
input,
new[] { "dd/MM/yyyy HH:mm:ss", "d/M/yyyy" },
new CultureInfo("en-GB"),
DateTimeStyles.None,
out dateTime);
If your input string is liable to change, TryParseExact allows you to define multiple formats as shown above, or alternatively, if it is always going to be with your current culture, just do DateTime.TryParse and do away with defining the format.
var okay = DateTime.TryParse(input, out dateTime);
If your format is always month/date/year and particularly in this case(if your date is 3rd Sept 2013) you can use:
string format = "MM/dd/yyyy";
string dateTime = "9/3/2013";
dateTime = (dateTime.Split('/')[0].Length == 1 ? "0" + dateTime.Split('/')[0] : dateTime.Split('/')[0]) + "/" + (dateTime.Split('/')[1].Length == 1 ? "0" + dateTime.Split('/')[1] : dateTime.Split('/')[1]) + "/" + dateTime.Split('/')[2];
DateTime fromdate = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
Do not provide the HH:MM:SS part in the format part
string format = "dd/MM/yyyy";
DateTime fromdate = DateTime.ParseExact(test.Text, format, CultureInfo.InvariantCulture);

DateTime.TryParseExact() rejecting valid formats

I'm parsing a DateTime value in an ASP.NET WebForms page and the date string keeps getting rejected by the DateTime.TryParseExact() method even though it clearly matches one of the supplied format strings.
It seems to fail on my development machine at home but work on the production server, so I am thinking of local date settings being involved, but this error occurs even when I supply an IFormatProvider (CultureInfo) object as a parameter
Here's the code:
DateTime startDate;
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"};
var errStart = row.FindControl("errStartDate"); //my date format error message
if (!DateTime.TryParseExact(txtStartDate.Text, formats, null, DateTimeStyles.None, out startDate))
{
errStart.Visible = true; //we get here even with a string like "20/08/2012"
return false;
}
else
{
errStart.Visible = false;
}
Note I'm giving a null FormatProvider in the above, but the same problem occurs when I provide a CultureInfo object as
(CultureInfo provider = new CultureInfo("en-US")) for this parameter.
What am I missing?
Try:
DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate)
Here you can check for couple of things.
Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}
This is the Simple method, Use ParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
This should work for you.
Try C# 7.0
var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
? dt : DateTime.Parse("1800-01-01");
string DemoLimit = "02/28/2018";
string pattern = "MM/dd/yyyy";
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(DemoLimit, pattern, enUS,
DateTimeStyles.AdjustToUniversal, out datelimit);
For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

Parse C# string to DateTime

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Categories

Resources