String format to convert datetime causes an error - c#

I try to convert persiandate to standard date.So my persian date has these formats (it means the user can enter these formats :
1392/1/1
1392/01/01
1392/01/1
1392/1/01
So i write a function to convert my persian date to standard date like this :
public DateTime ConvertPeersianToEnglish(string persianDate)
{
string[] formats = { "yyyy/MM/dd" };
DateTime d1 = DateTime.ParseExact(persianDate, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
PersianCalendar persian_date = new PersianCalendar();
DateTime dt = persian_date.ToDateTime(d1.Year, d1.Month, d1.Day, 0, 0, 0, 0, 0);
return dt;
}
But these function just can handle this formats 1392/01/01 and of the users enter other formats i got this error:
String was not recognized as a valid DateTime
Best regards

You're specifying MM and dd in your format, which require two digits. Just specify "yyyy/M/d" as the format - that should handle both 1 and 2-digit day/month values. (You can specify multiple formats instead, but in this case you don't need to. You might want to consider doing that just to be clear, but M and d will both handle two digit values with a leading zero with no problems.
Note that if you're just specifying a single format, you don't need to put it in an array. You can just use:
string format = "yyyy/M/d";
DateTime d1 = DateTime.ParseExact(persianDate, format,
CultureInfo.CurrentCulture,
DateTimeStyles.None);
However:
I suspect you want to specify the invariant culture, given that you don't want this value to affected by the culture
Your current approach of converting a date to the Persian calendar will simply not work.
Currently you're implicitly validating that the date given is in the Gregorian calendar, but then you're treating it as a Persian date. For example, 1392/02/30 is a valid Persian date, but not a valid Gregorian date.
Instead, you should use a culture which already uses the Persian calendar, and then specify that as the culture in your DateTime.ParseExact call. Then you don't need to do anything else afterwards.
You might alternatively want to consider using my Noda Time library - version 1.3 which includes the Persian calendar should be released in the next day or two.
Sample code using Noda Time:
var persian = CalendarSystem.GetPersianCalendar();
// The pattern takes the calendar system from the default value
var sampleDate = new LocalDate(1392, 1, 1, persian);
var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy/M/d")
.WithTemplateValue(sampleDate);
var date = pattern.Parse("1392/02/30").Value;
Console.WriteLine(LocalDatePattern.IsoPattern.Format(date));

Specify all formats in string[] formats:
string[] formats = { "yyyy/MM/dd", "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd" };

But these function just can handle this formats 1392/01/01
Because your yyyy/MM/dd format only support this value.
If your input can be
1392/1/1
1392/01/01
1392/01/1
1392/1/01
values, you should provide all formats that support these in your formats array in your DateTime.ParseExact method.
string[] formats = { "yyyy/MM/dd", "yyyy/M/dd", "yyyy/MM/d", "yyyy/M/dd" };
With these formats, if your value matches one of these formats, your parsing will be succeeded.

Related

Parsing "mm/dd/yy" string to "mm/dd/yyyy" date object in C#

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

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

String to DateTime Convert Issue

Hi I have a string in following format 23/03/2014 and I have tried to convert it to this format:
string npacked = Convert.ToDateTime(packeddate).ToString("yyyy/MM/dd");
But I am getting an error:
String was not recognized as a valid DateTime
Also tried this:
string npacked = DateTime.Parse(packeddate).ToString("yyyy/MM/dd");
but same error.
try with ParseExact with the format
string npacked = DateTime.ParseExact(packeddate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");
DEMO
Convert.ToDateTime is running a DateTime.Parse() on your string (23/03/2014). In the default culture (en-US) that is going to fail, since dates in that culture should be formatted MM/DD/YYYY. You need to switch to a different culture (like French) per MSDN:
// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try {
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
Calling "ToString" afterwards has no effect whatsoever on the parse attempt, it just formats the output of the parse.
It may be due to your system date time format. You have mm-dd-yyyy format in your system and you are trying to parse it in dd-mm-yyyy format. Try changing your system date format to dd/MM/yyyy.
Convert.ToDateTime(string) calls DateTime.Parse(string, CultureInfo.CurrentCulture) explicitly. That means your both lines are equivalent.
In your profile, it says you are from Dubai, United Arab Emirates. That's why I assume your CurrentCulture is probably ar-AE at first but your string matches it's ShortDatePattern and that's why it prints;
Convert.ToDateTime("23/03/2014", new CultureInfo("ar-AE")) // 23/03/2014
But you didn't tell us what is your CurrentCulture, we never know.. But looks like your current culture's date seperator is not / or your current culture doesn't have standart date format dd/MM/yyyy (which is unlikely for most of cultures) your both lines fail (first scenario is more likely).
You can easly parse your string with a culture that has / as a DateSeparator using DateTime.ParseExact method. This method let's you specify your custom date formats. We can use InvariantCulture for example;
var date = DateTime.ParseExact("23/03/2014",
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
Now, let's consider to it's representation with yyyy/MM/dd format.
/ specifier has a special meaning of "replace me with the current culture's date separator" in custom date formats. That means if your date seperator is not / (I assume it is not) your date.ToString("yyyy/MM/dd") results will be included your date seperator, not /.
For example, I'm from Turkey, my culture is tr-TR. My date seperator is . (dot) That's why this example;
date.ToString("yyyy/MM/dd"); // Prints 2014.03.23 not 2014/03/23
In such a case, you can use a culture which has / a date seperator as a second parameter in your ToString method (InvariantCulture for example) like;
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture) // Prints 2014/03/23
or you can escape your / character regardless which culture you use like;
date.ToString(#"yyyy\/MM\/dd") // Prints 2014/03/23

Console application string was not recognised as valid datetime

I have a excel sheet in which am taking a date column in this format "23/8/11 01:33:01:PM"
and am inserting it in sql 2008 using datarow but am getting a error
String was not recognised as valid datetime.
Can any one please help?
DateTime newdate = Convert.ToDateTime(row[8].ToString());
Here how Convert.ToDateTime method looks like when you decompile it;
public static DateTime ToDateTime(string value)
{
if (value == null)
return new DateTime(0L);
else
return DateTime.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}
As you can see, this method use DateTime.Parse method with your CurrentCulture. And if your string doesn't match your current culture date format, your code will be broken. That's the reason you get this error.
Use DateTime.ParseExact with "dd/M/yy hh:mm:ss:tt" format instead.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
string s = "23/8/11 01:33:01:PM";
DateTime newdate = DateTime.ParseExact(s, "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
Console.WriteLine(newdate);
Output will be;
8/23/2011 1:33:01 PM
Here a DEMO.
For your case;
DateTime newdate = DateTime.ParseExact(row[8].ToString(), "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
For more informations, take a look;
Custom Date and Time Format Strings
Convert.ToDateTime internally calls DateTime.Parse which by default will use the current culture of your application. If 23/8/11 01:33:01:PM is not a valid format for this culture then this method will fail.
For specific date formats it's best to use DateTime.ParseExact e.g.
DateTime.ParseExact("23/8/11 01:33:01:PM", "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
This approach makes your code culture independent which means the date will always be parsed correctly (given it's in the specified format).
This will work:
DateTime newdate = Convert.ToDateTime("8/23/11 01:33:01 PM");
I changed day and month and removed the colon a the end. But that is very specific. You need to know more about the dates passed to do that.

how to give format DateTime.Date?

DateTime dt = DateTime.Now
dt.Date is created to 31.10.2012 00:00:00 .it is created to dd.mm.yyyy format but i need dd/mm/yyyy. Can i use: return new DateTime(d.Year, d.Month, d.Day, 0, 0, 0); it will create to me dd/mm/yyyy solution?Please dont translate String.i need datetime...
The DateTime struct doesn't store any formatting information internally. If you want to output the DateTime instance as a formatted string, you just need to call ToString() with the proper format string:
var date = DateTime.Now;
var formattedString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need more information on exactly which specifiers to use in your format string, check out:
MSDN - Custom Date and Time Format Strings
Just the way to convert to string, DateTime itself has no format:
var result = DateTime.Now.Date
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
var dt = DateTime.Now;
var stringDt = dt.Date.ToString("dd/MM/yyyy");
In you case you can simply use :
dt.ToString("dd/MM/yyyy");
Anyway there al the string format you can use with DateTime : Here.
System.DateTime does not have any format. You can view its string representation in format.
Try this
Console.WriteLine(DateTime.Now.Date.ToString("dd'/'MM'/'yyyy"));
DateTime, numeric types and most other types do not store their values in a formatted way. Rather they store their data using a binary representation. If you want to display this data to the user, you must convert it to a string. This conversion involves formatting the data.
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy",
CultureInfo.InvariantCulture);
Or
Console.WriteLine("Date = {0:dd/MM/yyyy}", DateTime.Now);
Console.WriteLine converts the date into a string in order to write it to the console.
DateTime structure always has the Date and Time stored in it. If you need to extract the date alone as text you can do the following.
var date = DateTime.Now.ToString("d");
Console.WriteLine(date);
This will print the date as in the format as specified by the culture set in the system. The list of standard datetime format strings supported by dotnet framework can be found here

Categories