why this parse from string to DateTime fails in C#? - 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

Related

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

String was not recognized as a valid DateTime. Throws an Exception

I'm trying to convert current date to a specified format.
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I'm receiving the following exception.
String was not recognized as a valid DateTime.
My local TimeZone is (UTC+10:00)Melbourne.
What am I doing wrong here?
Your code (even if it worked), would do nothing. It would simply serialize and deserialize the date. I believe you're looking for this:
string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
It doesn't work because DateTime.Now.ToString() is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you):
14/01/2016 3:54:01 PM
Which is of the format:
dd/MM/yyyy h:mm:ss tt
Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff
Try this:
string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);
EDIT:
A better way to achieve the date in the format would be like
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
IDEONE DEMO

convert to stamp time format from string c#

I use javascript to pick a date and display the format as (11-05-2015 17:37)
and I try to parse it to date time as the code below
DateTime taskDate = Convert.ToDateTime(txtDate.Text);
and save it into my date base like
TO_DATE('" + createOn + "')
its give me and error call "String was not recognized as a valid DateTime."
anyone have any others method to parse it to stamptime ?
the txtDate.Text value is 27-05-2015 09:37.
Convert.ToDateTime uses your current thread culture format when converting from string to datetime.
If string you converting from has another format, you need to use DateTime.ParseExact and explicitly provide appropriate format.
For example, in you case it should be
DateTime taskDate = DateTime.ParseExact("11-05-2015 17:37", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
Also have a look to custom datetime format strings for your reference.
You can use DateTime.ParseExact or DateTime.TryParseExact
Check below code:
DateTime taskDate = DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture);
Or
DateTime taskDate;
if (DateTime.TryParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out taskDate))
{
//code if date valid
}
else
{
//code if date invalid
}

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 Converting

I am trying to convert a string into a DateTime and change its format from 05/06/2012 12:00:00 to 2012-06-05 12:00:00.000 to search in the database (SQL Server 2008 R2) DATETIME column type. The original date is coming from a calendar!
I tried this:
string Datereturn = row.Cells[9].Text;
DateTime dategiven = DateTime.ParseExact(Dategiven,
"YYYY-MM-DD hh:mm:ss[.nnn]", CultureInfo.InvariantCulture);
but it pops an error of invalid datetime
To parse 05/06/2012 12:00:00:
DateTime dategiven = DateTime.ParseExact(Dategiven,
"dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
To get a different formatted string:
string newFormat = dateGive.ToString("yyyy-MM-dd hh:mm:ss");
I suggest reading Custom Date and Time Format Strings on MSDN.
Also the different between parsing and formatting (in regards to DateTime):
Parsing means taking a string representing a datetime and getting a DateTime object from it
Formatting a DateTime is taking a DateTime object and getting a string from it, formatted as needed.
Can you try this
DateTime dategiven = DateTime.ParseExact(Dategiven, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

Categories

Resources