DateTime.ParseExact: String was not recognized as a valid DateTime - c#

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

Related

While pulling data from feed and transforming then getting Date conversion is not working

We are getting some data from feed where date is something like "28-07-2020 09:11:57 AM" when i am trying to convert it it is always giving error that
"String was not recognized as a valid DateTime."
I have used many methods like Convert.ToDateTime, DateTIme.Parse , DateTime.parseExact but all are having same error.
string s = "28-07-2020 09:09:57 AM";
var dt= DateTime.ParseExact(s,"M/d/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);
DateTime dt2= Convert.ToDateTime(s);
DateTime dt3=DateTime.Parse(s);
Can someone please suggest what is the issue in date format. We need to change it regardless culture as it is a window application and running on diff machines.
You were close, this works for me:
string s = "08-07-2020 09:09:57 AM";
var dt = DateTime.ParseExact(s, "M-d-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Note matching dashes instead of slashes in pattern.
After many try and combination below worked
string s = "28-07-2020 09:09:57 AM";
var dt = DateTime.ParseExact(s, "d-MM-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
This works for me (https://dotnetfiddle.net/MqwLLb):
Input:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string s = "28-07-2020 09:09:57 AM";
var dt= DateTime.ParseExact(s,"dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine("dt => " + dt);
}
}
Output:
dt => 7/28/2020 9:09:57 AM
You can use TryParseExact method, it is quite useful if you are not sure about the incoming string value, also it is giving the result of parsing process as a boolean which makes easier to check if everything is right, and you can play with DateTimeStyles for adjusting output.
string s = "28-07-2020 09:09:57 AM";
var dt = new DateTime();
var result = DateTime.TryParseExact(s, "dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal,out dt);

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

String To DateTime Exception

I have this String :
05/09/2013 23:23
And i want to convert it to DateTime with this:
DateTime alarmDateTime = new DateTime();
alarmDateTime = DateTime.ParseExact(date, "MM/dd/YYYY HH:mm", null);
And i get this Exception:
String was not recognized as a valid DateTime.
Any idea why it happens?
I think the year should be lower case 'y'. There is also no need to instantiate the date time on the first line as the value is overwritten on the second.
DateTime alarmDateTime = DateTime.ParseExact(date, "MM/dd/yyyy HH:mm", null);
If date seperator in your system is "/" then just changing YYYY to yyyy will work.
If it is not then use this
string date = "05/09/2013 23:23";
DateTime alarmDateTime = new DateTime();
alarmDateTime = DateTime.ParseExact(date, "MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);

why this parse from string to DateTime fails in C#?

I have a DateTime eventDate field in my Mysql table which I compose from the inputs when I insert it in db:
cmd.Parameters.Add("?eventDate", MySqlDbType.DateTime).Value = DateTime.ParseExact(txtEventDate.Text + " " + txtEventTime.Text,
"MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
and is saved nice:
2011-05-05 10:20:00
Now, when I read it from DB I want to split it but it fails if I do like this:
txtEventDate.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).Date.ToShortDateString();
txtEventTime.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).TimeOfDay.ToString();
saying that:
String was not recognized as a valid DateTime.
Do you see any issue? I cannot figure out where I am wrong...
It seems superfluous to convert it to a string and parse it as a datetime and this may introduce problems with enexpected date formats.
If you have a Datetime in the database you could also do
txtEventDate.Text = Reader.GetDatetime(7).ToShortDateString();
txtEventTime.Text = Reader.GetDatetime(7).TimeOfDay().ToString();
To format DateTime try something like this...
DateTime date = Reader.GetDateTime(7);
txtEventDate.Text = date.ToString("MM/dd/yyyy");
txtEventTime.Text = date.ToString("HH:mm:ss");
You have to provide the right format. That may be:
yyyy-dd-MM HH:mm:ss

Convert Date String to DateTime

I have to convert a date string to a DateTime object as follows
tmpdate = "27-Apr 14:53";
TheDate = DateTime.ParseExact(tmpdate, "DD-MMM HH:mm", CultureInfo.InvariantCulture);
I keep getting exceptions about the string not being a valid date time. I've tried adding in the year as well with no luck. Any suggestions?
Try dd-MMM HH:mm - note lowercased dd.
try with little d :
TheDate = DateTime.ParseExact(tmpdate, "dd-MMM HH:mm", CultureInfo.InvariantCulture);
string tmpdate = "27-Apr 14:53";
DateTime TheDate = DateTime.ParseExact(tmpdate, "dd-MMM HH:mm", System.Globalization.CultureInfo.InvariantCulture);

Categories

Resources