I am trying to convert my string formated value to date type with format dd/MM/yyyy. It runs fine but when I enter fromdate(dd/MM/yyyy) in textbox its fine and todate(dd/MM/yyyy) in textbox then it gives an error that string was not recognized as a valid datetime.What is the problem exactly i dont know. same code run on another appliction its run fine but in my application it shows Error.
Below I have used array for required format and split also used.
string fromdate = punchin.ToString();
string[] arrfromdate = fromdate.Split('/');
fromdate = arrfromdate[1].ToString() + "/" + arrfromdate[0].ToString() + "/" + arrfromdate[2].ToString();
DateTime d1 = DateTime.Parse(fromdate.ToString());
try with DateTime.TryParseExact as below
DateTime date;
if (DateTime.TryParseExact(inputText, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
if you know the format of input date time you don't need to do any string manipulation.
But you need to give correct Date and Time Format String
I got 5/13/2013 12:21:35 PM in string fromdate
Use DateTime.TryParseExact, You don't have to split your string based on / and then get first three items from the array instead you can simply do:
DateTime dt;
if (DateTime.TryParseExact("5/13/2013 12:21:35 PM",
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//date is fine
}
Using single d and single M as it can accomodate single digit as well as double digits day/Month part. You can simply pass punchin as the string parameter, Calling ToString on string types is redundant.
Try :
DateTime.ParseExact(fromdate, "MM/dd/yy", CultureInfo.InvariantCulture)
Obviously you can reformat the above, and use different providers by creating an instance of CultureInfo related to the string you are parsing, and you can modify the format string to reflect that culture or to accommodate more date parts
Related
My dateformat is dd/MM/yyyy.
I have a date column in my file with values like 1/08/2019 to 31/08/2019.
But I'm getting the following error when processing that file:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
You've specified in your format string that the days and months must be double digits, but it appears that your input can be single digits.
In order to solve this, you need to specify a single digit in the format string by using a single d for the day portion (and a single M for the month, too).
It's also safe to use a single digit in the format string, since it will handle both single and double digits.
So your format string should look like: "d/M/yyyy"
For example, these all work:
var a = DateTime.ParseExact("1/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var b = DateTime.ParseExact("1/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var c = DateTime.ParseExact("01/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var d = DateTime.ParseExact("01/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
difficult to say as you show the error but not the actual code, as you have dates in your file of differennt format, like d/MM/yyyy and dd/MM/yyyy try to use TryParse instead of ParseExact and if the TryParse fails with one format ( d/MM/yyyy ), then do another TryParse with the second format ( dd/MM/yyyy ) that way you should be able to cover both cases.
Again, without seeing the code it is difficult to give more detailed feedback.
also you could use an approach with TryParseExact and multiple format strings, like shown here:
var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" };
if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
return dateValue;
see this SO answer: https://stackoverflow.com/a/17859959/559144
I am working on an ASP.NET Mvc application with C# and facing a problem when I try to upload a .CSV file in order to save its data to database.
The problem comes from the date column of the .CSV file. There are two formats of date used in that column. The first one is "mm/dd/yyyy" that I have no problem to parse to a DateTime object by the following code:
// for the date : 09/30/2014
DateTime tempo = Convert.ToDateTime("09/30/2014");
The second format is "mm/dd/yy". The same method above doesn't work for this format and throws an exception
// for the date : 09/30/14
DateTime tempo = Convert.ToDateTime("09/30/14");
// this line throws ;
// [09/30/14] String was not recognized as a valid DateTime. exception
Is there a solution which works for both of date formats ?
Thanks for your help.
First, mm specifier is for minutes, MM specifier is for months. Convert.ToDateTime method uses your CurrentCulture by default. That means MM/dd/yy is not a standard date and time format your CurrentCulture but MM/dd/yyyy is.
You can use custom date and time formatting string like;
string s = "09/30/14";
DateTime date;
if(DateTime.TryParseExact(s, "MM/dd/yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Successfully parse
}
Be aware "/" custom format specifier has a special meaning of replace me with the current culture or supplied culture date separator. That means even if your string and format matches, you parsing will fail.
Is there a solution which works for both of date formats ?
DateTime.TryParseExact method has an overload that takes formats as a string array. If your string matches one of your formats, it will returns true.
string s = "09/30/14";
sstring[] formats = {"MM/dd/yy", "MM/dd/yyyy"};
DateTime date;
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Successfully parse
}
Also you can see all standard date and time patters of your CurrentCulture like;
foreach (var format in CultureInfo.CurrentCulture.
DateTimeFormat.
GetAllDateTimePatterns())
{
Console.WriteLine (format);
}
string strHijdt ="29-02-1435";
DateTime hdt = DateTime.ParseExact(strHijdt, "dd/MMM/yyyy HH:MI24",
CultureInfo.InvariantCulture);
Getting error while convert to string("29-02-1435") to datetime
2/1435 has 28 days only
so, below will work
string aa="28-02-1435";
DateTime hdt = DateTime.ParseExact(aa, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(hdt.ToLongDateString());
DEMO
since you have given input as 29-02-1435 even you provide correct date time format (dd-MM-yyyy) you will get error for the invalid date
Two problems here:
1. As mentioned above, expected format for does not match string (there is no time, different separator)
2. If your date string is in Hijri calendar, you should either provide correct culture explicitly or use system culture (pass null for IFormatProvider):
string strHijdt = "29-02-1435";
var culture = CultureInfo.GetCultureInfo("ar-SA");
DateTime hdt = DateTime.ParseExact(strHijdt, "dd-MM-yyyy", culture);
I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind
I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)