string strdate="15/06/2010";
DateTime dt =
DateTime.Parse(strdate,
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);
i cannot able to get the datetime value as dd/mm/yyyy.
it is giving exception 'string is not recognized as a valid datetime'
oly if it is in 06/15/2010 it is working. how to get the same format in dt.
Well, presumably your thread's current culture expects MM/dd/yyyy. If you want to use dd/MM/yyyy then you should specify that explicitly. Personally I prefer ParseExact instead of Parse, as that gives more control. I would use something like:
DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
Note that if this is user input, you may want to use TryParseExact instead.
You're currently using the current culture, which seems to be set up for US style date formats. Try this instead:
DateTime.Parse(strdate, System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"));
This tells the function to use UK date style format which works. You might want to change the en-GB to whatever culture your dates will be in. If you have many calls where the culture is important it might also be worth to set it for the whole thread rather than call by call.
Related
I was trying to validate a date read from app.config file using DateTime.TryParse() method. However, it returned true when the input was "12/05/201". This was actually a typo, and should have been, "12/05/2018". When I stepped through the code it automatically converted the date to "12/05/0201" and returned true. However when I used DateTime.TryParseExact(), it correctly returned false for the above input. So, should we always use DateTime.TryParseExact()? I am little confused because earlier I used use DateTime.TryParse() whenever I had to validate a date string! Both the code is given below:
Boolean isValidStartDate = DateTime.TryParse(startDate, out DateTime startDateVerified);
CultureInfo enUS = new CultureInfo("en-US");
Boolean isValidStartDate = DateTime.TryParseExact(startDate,"MM/dd/yyyy",enUS, DateTimeStyles.None, out DateTime startDateVerified);
Thanks
The year 201 being invalid is business logic - if you want to have logical safeguards on your imported data (and you should), do them explicitly. With C# you can easily add an extension method to DateTime if you want, something like
public static DateTime ParseDateWithSanity(this DateTime, string date)
{
dt = DateTime.Parse(date);
if dt.Year < 1900
{
throw BadInputException()
}
}
Best way to Validate date depends upon the use case and input data source and its formate
DateTime.TryParse is parsed using formatting information in the current DateTimeFormatInfo object so let's say if you use TryParse "12/05/201" it will return the parsed data according to your current culture settings. Which is "12/05/0201" ie in date format "MM/DD/YYYY"
Its always good practice to specify date formate and culture variance while parsing date and use TryParseExact instead of TryParse
(Note: To know about current culture settings you can look for a member of classes CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture)
I am using DateTime.TryParse method in my program to judge if a string value is DateTime, then I notice this:
DateTime.TryParse("9.08", out DateTime dt)
// true
DateTime.TryParse("2.52", out DateTime dt)
// false
Why would this happened ?
DateTime.TryParse is parsed information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.
Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales
In some cultures, DateTime separator is . rather than /.
On my computer.
DateTime.TryParse will Parse "9.08" be this year '09/08', 2018/09/08 is a valid datetime, so it's true.
DateTime.TryParse will Parse "2.52" be this year '02/52', but there isn't 52nd days on February, 2018/02/52 isn't a valid DateTime, so it will be false.
I would use DateTime.TryParseExact to Parse DateTime because you can set your CultureInfo and Parse DateTime string be parameters and ensure that conforms to your expected format.
DateTime.TryParseExact("09.08",
"MM.dd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dt);
As per DateTime.TryParse documentation:
returns a value that indicates whether the conversion succeeded.
As it couldn't parse "2.52" to any valid date, it returned false.
Except you are trying to understand every time string conversion of .NET
Otherwise, you should not able to answer "why exactly would that happened?"
DateTime.TryParse is just a simple condition handling to prevent you getting an error when you do
Convert.ToDateTime(dateString)
Thus, DateTime.TryParse = false means you should not do Convert.ToDateTime to that string.
Oppositely, if a string to DateTime.TryParse = true, then it means that string should match the expectation of .NET date string (it means .NET know how to convert that string to DateTime).
I am filling my Grid from database. On RowEditing event I am fetching data from grid to TextBox. This is the code that I am using
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"]).ToShortDateString();
This gives me date in 02-06-2015 format but I want to display date in 02-Jun-2015 format.
You could use the ToString method and pass there the format you want.
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"]).ToString("dd-MMM-yyyy");
At the bottom of this, you will find also other useful formats.
From DateTime.ToShortDateString method
The value of the current DateTime object is formatted using the
pattern defined by the DateTimeFormatInfo.ShortDatePattern property
associated with the current thread culture.
That means, your CurrentCulture's ShortDatePattern is dd-MM-yyyy. If you want abbreviated month name of your CurrentCulture, you can use MMM specifier instead.
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"])
.ToString("dd-MMM-yyyy");
Remember, if your CurrentCulture is not english-based one, this MMM specifier will generate a different name than Jun. In such a case, you can provider an english-based IFormatProvider (like InvariantCulture) as a second parameter in ToString method like;
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"])
.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
To get the DateTime format, box the string into DateTime and use the the formatting string via ToString(), like :
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"]).ToString("dd-MMM-yyyy");
visit this link of MSDN for complete details:
https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
Simply use this
Convert.ToDateTime(YourDataSet.Tables[0].Rows[0]["Date"]).ToString("dd MMM yyyy");
OR
Convert.ToDateTime(YourDataSet.Tables[0].Rows[0]["Date"]).ToString("dd/MMM/yyyy");
Or what ever you want
Like this:
txtDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BuyDate"]).ToString("dd MMM yyyy");
See here: examples how to format DateTimes.
In your case dd-MMM-yyyy wold be the correct pattern.
As mentioned, you don't have to use string.Format(), the .ToString() does also allow to pass the pattern.
Please note, that you should also consider to keep the information as DateTime (not string) and format it in a Binding (if you are using DataBinding) that would sepparate the view from the underlying data
I am using the code below to check the datetime and it is working fine in my machine but once after deployment, I am getting
"String was not recognized as a valid DateTime."
Please provide me the solution to work in all machine.
DateTime date1 = DateTime.Parse("16/05"); MM/dd
string todaydate = DateTime.Now.ToString("MM/dd");
if (Convert.ToDateTime(todaydate) > Convert.ToDateTime(date1.ToString("MM/dd")))
{ //Logic }
Honestly, since both answer didn't satisfied me, here is my two cent..
Let's look at your code line by line;
DateTime date1 = DateTime.Parse("16/05");
DateTime.Parse uses your CurrentCulture settings by default if don't provide any IFormatProvider as a second parameter on it's overloads. That means, if your one of standard date and time patterns of your CurrentCulture includes dd/MM (or your current culture DateSeparator since / format separator has a special meaning of replace me with current culture date separator) format, this parsing operation will be successful. That means this line might throws FormatException that depends on the current culture settings.
string todaydate = DateTime.Now.ToString("MM/dd");
DateTime.Now returns a local current time. With it's ToString() method you try to get it's string representation with MM/dd format. BUT WAIT! You used / format specifier again and still, you didn't use any IFormatProvider. Since this format specifier replace itself with current culture date separator, your todaydate might be 05/16, 05-16 or 05.16. That's totally depends on what date separator your current culture use.
Convert.ToDateTime(todaydate)
Convert.ToDateTime method uses DateTime.Parse explicitly. That means,since you didn't provide any IFormatProvider it will be use your CurrentCulture again and it's standard date and time formats. As I said, todaydate might be 05/16, 05-16 or 05.16 as a result. But there is no guarantee that your current culture parse this string successfully because it may not have MM/dd in it's standard date and time formats. If it parse "16/05" successfully, that means it has dd/MM format, in such a case, it definitely can't have MM/dd as a standard date and time format. A culture can't parse dd/MM and MM/dd formats at the same time. In such a case, it can't know that 01/02 string should parse as 2nd January or 1st February, right?
Convert.ToDateTime(date1.ToString("MM/dd"))
Same as here. As todaydate string, this will create "05/16" (it depends on current culture date separator of course) result and still there is no guarantee to parse this successfully.
And as said in comments, there is no point to parse your string to DateTime and get it's same string representation as well.
I strongly suspect you try to compare your current date is bigger than your parsed DateTime or not, you can use DateTime.Today property to compare with it. This property gets DateTime as current date part plus midnight as time part. For example;
DateTime dt;
if(DateTime.TryParseExact("16/05", "dd/MM", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if(DateTime.Today > dt)
{
// Your operation
}
}
DateTime dt = DateTime.ParseExact("16/05", "dd/MM", CultureInfo.InvariantCulture);
if (DateTime.Today > dt)
{
// your application logic
}
DateTime dt = // From whatever source
if (DateTime.Now.Ticks > dt.Ticks)
{
// Do logic
}
I have date string in format dd-MMM-yyyy and want to convert this to datetime, when I use below code
DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null)
it causing an error
String was not recognized as a valid DateTime.
When I modify above code
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null)
then I got date time in format (mm/dd/yyyy) : 10/20/2012 12:00:00 AM
But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.
You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This
You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.
In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:
// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);
// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");
Also note that the mm format specifier represents minutes; months are represented by MM.
Edit: 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.
However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime, which renders the date and time under the current culture (which, in your case, assumes the US culture).
To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.
You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!