Parsing dates error - c#

string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
//MessageBox.Show(temp);
temp = temp[0].ToString() + temp[1].ToString() + temp[2].ToString() + temp[3].ToString() +
temp[4].ToString() + temp[5].ToString() + temp[6].ToString() + temp[7].ToString() +
temp[8].ToString() + temp[9].ToString();//converting to dd-MM-yyyy
labeldate = DateTime.ParseExact(temp,"dd-MM-yyyy",
CultureInfo.InvariantCulture);
I use the above code to convert string (dd/mm/yyyy format) into datetime type. It works fine on my computer. But the same gives an error on other computers saying string was not recognized as datetime. On further investigation. I saw that in other computers temp showed 1/1/2013 or 11/3/2013 whereas on mine it would show 01-01-2013 or 11-03-2013. I can't seem to solve this. Any help?

This is likely a culture issue. Use .ToString(CultureInfo.InvarientCulture) and you'll get the same result regardless of the culture set on the computer.

If all you are doing is trying to get the date portion of the date time you can simplify your code to
string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
labeldate = DateTime.Parse(temp).Date;
As for the culture problem wilsjd mentioned. If ToolTipText is using the default culture rules for however that text is being entered the parser should use the same rule when it tries to parse it back out.

Related

How Can I get Today's date with UFTC stamp in c#?

Is there an inbuild DateTime functionality that could give me a string format of today's date as 2020-12-22T13:36:45 Etc/UTC (+00)
I can think of these ways:
var date = DateTime.Now;
var result = date.ToString("yyyy-MM-ddTHH:mm:ss") + " Etc/UTC (+00)";
Console.WriteLine(date.ToString("yyyy-MM-ddTHH:mm:ss Etc/UTC (+00)"));
//Gives '2020-12-23T10:59:59 EAc/UTC (+00)' - incorrect t replaced by A
Console.WriteLine(result);
//Gives '2020-12-23T10:59:59 Etc/UTC (+00)' Correct,
As you can see I can get the correct format, though I am not sure this is the best solution, as it looks very artificial.
Is there a better way to format the string?
how about date.ToString("yyyy-MM-ddTHH:mm:ss 'Etc/UTC (+00)'")
or if you need the real timezone, date.ToString("yyyy-MM-ddTHH:mm:ss 'Etc/UTC ('zzz')'")

How to remove time in second after retrieve from database?

i have this label retrieve time from database and display in label. but time in database also consist of second for example 03:45:29, how can i remove the time in second to become 03:45 in the label after retrieve it. this is my code:LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();
Assuming dr is a SqlDataReader or similar, you probably want to cast to DateTime, then format the value appropriately:
DateTime dateTime = (DateTime) dr[3];
string formatted = dateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
LabelDateMarker.Text += " " + formatted;
Here yyyy-MM-dd HH:mm is a custom date/time format string indicating that you want the hours and minutes after the ISO-8601-formatted date part.
I've used the invariant culture when formatting to avoid this giving unexpected results in locales that don't use the Gregorian calendar by default.
(I've assumed the value is always non-null. If it might be null, you should check it with dr.IsDBNull(3) first.)
Use a format string for this
((DateTime)dr[3]).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
instead of
dr[3].ToString();
For more information have a look at the available formats at the MSDN

String was not recognized as a valid DateTime when using DateTime.ParseExact

I have below piece of code to log the message. Since I wanted to have the log for each date I tried to retrieve current date and then tried to create log file with that particular date with format path/dd_mm_yyyy_LogFile.txt. Before that I had to retrieve current date without time.
StreamWrite sw=null;
var d = Convert.ToString(DateTime.Today.ToShortDateString());
var date = DateTime.ParseExact(d, "dd_MM_yyyy", CultureInfo.InvariantCulture);
//Error in the above line
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + d + "_LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);
But am getting String was not recognized as a valid DateTime. I followed many other posts like changing the "dd_MM_yyyy" to "dd-MM-yyy" or to "d-m-yyyy" but unfortunately am still hitting the same error. What else am missing here? Below screenshot for reference. If you see the screenshot, I've proper d value fetched. But still the above exception.
As I can see from the picture, you actually want "M/d/yyyy" format:
String d = #"2/26/2016"; // d's value has been taken from the screenshot
DateTime date = DateTime.ParseExact(d, "M/d/yyyy", CultureInfo.InvariantCulture);
Create d like this instead:
var d = DateTime.Today.ToString("dd_MM_yyyy");
ToShortDateString() does not have the format you want.
Your format string in Parse method should exactly match the one produced by ToShortDateString. e.g. this works with me:
var d = Convert.ToString(DateTime.Today.ToShortDateString());
Console.WriteLine(d);
var date = DateTime.ParseExact(d, #"MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);
output:
02/26/2016
02/26/2016 00:00:00
Look at the screen shot you posted. The runtime value of the string is:
"2/26/2016"
So the format string should be:
"M/dd/yyyy"
or:
"MM/dd/yyyy"
By using those other format strings, you're explicitly telling the system to use that exact format. And the string you have doesn't match that format. Hence the error.

DateTime parsing error while parsing dd/MM/yyyy format. String was not recognized as valid datetime

I create a string using values from certain page elements in my web user control as below
string bookingdate = ddlDate.SelectedItem.Text
+ "/" + ddlMonth.SelectedValue + "/"
+ ddlMonth.SelectedItem.Text.Substring(4, 2);
and getting "String was not recognized as a valid DateTime." error on the following line
cmd.Parameters.Add(new SqlParameter("#ArrivalDate", SqlDbType.DateTime)).Value =
DateTime.ParseExact(bookingdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
How can I alter the value of this string "bookingdate" to troubleshoot the problem.
So ddlMonth contains items in this format (you posted the link to your page):
<option value="08">Aug 14</option>
Now you're trying to extract the month and year part from it:
ddlMonth.SelectedValue + "/" + ddlMonth.SelectedItem.Text.Substring(4, 2)
Your format string is this: dd/MM/yyyy
Do you already see the problem? The format string expects four digits for the year.
Instead use this format string: dd/MM/yy
DateTime.ParseExact(bookingdate, "dd/MM/yy", CultureInfo.InvariantCulture);
As I can understand you need Indian Date Format that is dd/mm/yyyy. So in your code, pass parameter as string and in sql handle it using Convert(date,Convert(datetime,#ArrivalDate,103)). Use date as your datatype if you need only date and is on Sql 2008 or above otherwise
Convert(datetime,#ArrivalDate,103) and leave your datatype as datetime
In cs:
cmd.Parameters.AddWithValue("#ArrivalDate", bookingdate);

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources