ParseExact DateTime error - c#

I have a list of DateTime as strings: dd.MM.yyyy H:mm:ss (The time is 24 hours format but the hour is single digit: 6 instead of 06)
14.12.2016 6:20:21
15.12.2016 8:30:00
16.12.2016 12:30:00
17.12.2016 14:33:00
18.12.2016 18:10:00
I am trying to parse exact the string values as a DateTime object like this:
DateTime.ParseExact(dt, "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture) (dt is the string value from the list)
The problem is I get an error saying the string is not a valid DateTime ...
With the current format, the first and second values in the list work fine, when it get's to the third 'boooom' I get the error.
Am I missing something in my format?

Use the overload of DateTime.ParseExact that accepts an array of valid formats:
string[] formats = { "dd.MM.yyyy H:mm:ss", "dd.MM.yyyy HH:mm:ss" };
var result = DateTime.ParseExact(dt, formats, CultureInfo.InvariantCulture, 0);
UPDATE: As others have noted, H should match both one-digit and two-digit hours, so something else is going on. The following code runs successfully on my system (.NET 4.5.2):
string dt = "16.12.2016 12:30:00";
var result = DateTime.ParseExact(dt, "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture);

I had to parse exact the using Hour, Minute, and Second then use the ToString method to convert to a Month, day, and year format
$myStringDate=[Datetime]::ParseExact($item.myDateObject,'MM/dd/yyyy H:mm:ss',$null).ToString('MM/dd/yyyy')

Related

c# tryParseExact not recognized as valid datetime

I am trying to parse a string that I'm trying to parse.
when I use var newDt = Convert.ToDateTime("3/6/2019 12:00:00 AM +00:00");
It gives me the date with a different timezone. I would get a date time of 3/5/2019 4:00AM
I would like it to parse and return the same date time as the string.
I've tried
var newDt = DateTime.ParseExact("3/6/2019 12:00:00 AM +00:00", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
I get the error
System.FormatException: 'String was not recognized as a valid
DateTime.
How can I parse the date "3/6/2019 12:00:00 AM +00:00" to return a datetime with the same value of 3/6/2019 12AM
You probably have UTC−08:00 time zone (which I assume your Convert.ToDateTime code part returns 3/6/2019 4:00AM not 3/5/2019 4:00AM) in your machine and that's why when you parse it with offset value, you will get 4 hour added value.
If your string contains UTC offset value, it would be better to parse it to DateTimeOffset instead of DateTime.
var newDt = DateTimeOffset.ParseExact("3/6/2019 12:00:00 AM +00:00",
"M/d/yyyy h:mm:ss tt zzz",
CultureInfo.InvariantCulture);
Then you can use it's .DateTime property to get the value you expected.

string was not recognized as a valid datetime while Converting Date from Hijri to Gregorian date

I am Trying to Convert Hijri Date into Gregorian Date I was following this article and My Code is as follows :
var cultureInfo = CultureInfo.CreateSpecificCulture("ar-sa");
string date = "19/12/36 12:00:00 ص";
Getting
string was not recognized as a valid datetime
error in below line
DateTime tempDate = DateTime.ParseExact(date, "dd/MM/yyyy", cultureInfo.DateTimeFormat, DateTimeStyles.AllowInnerWhite);
lblDate.Text = tempDate.ToString("dd/MM/yyyy");
I am getting string was not recognized as a valid datetime. Please can somebody tell me whats wrong with this code?
I think I'm on the right way but.. Let's try something at least.
First of all, DateTime values are always in the Gregorian calendar, basically. There's no such thing as "A DateTime in a UmAlQuraCalendar calendar" - which is used by ar-sa culture - you have to use the UmAlQuraCalendar to interpret a DateTime in a particular way.
Second, when you use DateTime.ParseExact for parsing your string, your string and format does match exactly based on culture you use. Since ص
character seems AMDesignator of ar-sa culture, you should provide tt specifier with your time part as well.
string s = "19/12/36 12:00:00 ص";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yy hh:mm:ss tt", CultureInfo.GetCultureInfo("ar-sa"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Note: Since TwoDigitYearMax is 1451 of UmAlQuraCalendar calendar, your 36 will be parsed as 1436 with yy format specifier.
This perfectly parse your question but WAIT! What will be the result? Here it is.
02/10/2015 00:00:00
Why? As I said in the top, you have to use the UmAlQuraCalendar to interpret this DateTime instance.
UmAlQuraCalendar ul = new UmAlQuraCalendar();
Console.WriteLine(ul.GetYear(dt)); // 1436
Console.WriteLine(ul.GetMonth(dt)); // 12
Console.WriteLine(ul.GetDayOfMonth(dt)); // 19

Convert string into mm/dd/yyyy format

I have following strings in different formats:
16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014
I need to convert all the above strings into mm/dd/yyyy format in c#.
I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".
I have also tried to use to Convert.ToDateTime() but it is also not working.
Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??
Any help on this would be greatly appreciated.
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this
DateTime.ParseExact("16-05-2014",
new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None);
With this you can parse all your formats at once.
For more information about the format settings, see the official docs.
Few things:
Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?
Secondly, you're using mm which represents Minutes, not Months. You should use MM.
Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /
Supply a collection of different formats matching your input:
string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy",
"yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
You might find the following method useful to accept whatever date format you want and convert it to DateTime:
public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
if (string.IsNullOrEmpty(DateTimestring)) return null;
else
{
DateTime datetimeNotNull;
DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
return datetimeNotNull;
}
}
Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.
You can use it like this:
DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");
If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.
As others have pointed out, months are MM not mm (minutes).
On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:
var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");

String conversion to datetime independant of string format

I want to convert a string to datetime format.
The thing is that the string comes in different formats.
For instance, in the code below, strDate can be "2/20/2014 1:41:57 PM" or "20/02/2014 13:44:56".
Convert.ToDateTime(strDate) executes well just for one format (the one on the user browser settings) and generates an error for the other.
How can I successfully convert the string to datetime independently of the string format?
Thanks
DateTime dt = Convert.ToDateTime(strDate);
You can use DateTime.TryParseExact or Datetime.ParseExact with multiple formats like:
string dateStr = "20/02/2014 1:41:57 PM";
string[] dateFormats = new[]
{
"d/M/yyyy h:mm:ss tt",
"M/d/yyyy h:mm:ss tt",
};
DateTime dt;
if (DateTime.TryParseExact(dateStr,
dateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid dates for formats
}
else
{
//invalid date
}
the problem with this approach is that it would give you inconsistent results with strings like 10/02/2014 1:41:57 PM, The above code would parse it as 10th Feb 2014, not as October 2nd 2014, to avoid this you can customize your client side to return date in specific format and then parse accordingly.
you want DateTime.Parse() or DateTime.TryParse()
i.e.
DateTime dt;
if(DateTime.TryParse(stringDate, out dt)
{
//successful datetime conversion
}
if you know the string will be one of several exact formats, you can use DateTime.TryParseExact() and pass in a string array of each format (the second overload).

Parsing datetime of the format "2013-Jan-31" throws error

I have a datetime column in database.
DateTime end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Why isn't this working?
This is not working because MM would mean January to be 01. If this is the format of the date you're trying to parse, try the format "yyyy-MMM-dd".
Hope this helps
Try like this;
DateTime a = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine (a);
Output:
31.01.2013
Look at from MSDN Custom Date and Time Format Strings
To use such a name of the month you need to take "MMM" so it will be
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
MM represents a two-digit numerical month (such as "01").
MMM represents the abbreviated month (such as "Jan").
Which means that you need
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for a list of string format specifiers.

Categories

Resources