Unable to parse DateTime from a string - c#

string dt = "10/25/2010 11:40:05 PM";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
How to parse that dt?
UPDATE:
In my case DateTime can be represent as "25.10.2010 11:40:05" or "10/25/2010 11:40:05 PM"
Is these any "generic" method to parse it without changing CurrentCulture?

Use a custom Date and Time format string, using either ParseExact or TryParseExact.
DateTime dateTime;
DateTime.TryParseExact(
dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime
);
The string cannot be parsed as a Russian DateTime representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture which is a US like culture (it represents no specific culture, but is modeled after the en-US one).

Try using ParseExact instead:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))

var result = DateTime.ParseExact(dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception

Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)
I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:
string text = "10/25/2010 11:40:05 PM";
string pattern = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(text, pattern,
CultureInfo.InvariantCulture);
If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.

Try something like this:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));

Related

Cannot Roundtrip DateTime Format

I convert a DateTime to a string using a custom format:
var s = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
Now, when I try to reverse it:
var dt = DateTime.ParseExact(s, "yyyy/MM/dd hh:mm:ss");
I get an exception about the string not being in a valid format. I even tried to pass CultureInfo.InvariantCulture, but no luck.
Any ideas?
If you use ToString method with one argument, then it uses CurrentCulture as format provider that can change the "/" symbol to specific for your culture ("." for example).
If InvariantCulture is acceptable for you, try to use this code:
var s = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss", CultureInfo.InvariantCulture);
var dt = DateTime.ParseExact(s, "yyyy/MM/dd hh:mm:ss", CultureInfo.InvariantCulture);
I had mistakenly forgotten the last parameter to ParseExact, which whould be CultureInfo.InvariantCulture. In the end, however, the problem was not having HH instead of hh.

How to convert a date string from "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt"?

I need to compare two date format strings:
dateString in "dd-MMM-yy" format
with
referenceDateString in "M/dd/yyyy hh:mm:ss tt" format respectively.
For that, I need to convert the dateString = "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt".
However, Got an error while trying to do that:
"Error: string was not recognized as a valid datetime".
The C# code I used given below.
string dateString = "19-Dec-14";
string AsofDate = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Edit 1:
In the actual code the dateString obtaining after reading a csv file which is supplied as "19-Dec-14", that's why it's in the string format.
Please help, am pretty new to C#. Thanks.
Habib already gave the answer on his comments, I try to add it as an answer;
From DateTime.ParseExact(String, String, IFormatProvider)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
In your case, clearly they don't. First, you need to parse your string to DateTime with proper format (which is dd-MMM-yy with an english-based culture), then you can get the string represention of your DateTime with specific format.
string s = "19-Dec-14";
DateTime dt;
if(DateTime.TryParseExact(s, "dd-MMM-yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Dump();
// Result will be 12/19/2014 12:00:00 AM
}
It's not entirely clear what you are trying to do, but in order to parse that date you have on the first line, you would use something like this:
DateTime AsofDate = DateTime.ParseExact(dateString, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
Note a couple things here: I've changed the data type of AsofDate from string to DateTime because that's what DateTime.ParseExact returns. Also, I've modified the custom format string to match the format of the string you are trying to parse as a date ("19-Dec-14").

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
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.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

System DateTime Format is changed

I have Window 7 installed in my computer. The problem is that the system date format is changed some time if computer is restarted. I need to make the date format fixed but don't know how. I have application built in mvc 3 and have code for string to datetime conversion. If system datetime format doesn't match with string it show error that
string is not in proper format for converting into datetime which looks for system datetime. The exception is thrown in following code:
DateTime startDate = Convert.ToDateTime(start);
where,
string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss");
Or, Is there any alternatives so that I can change in code that works all the time despite the system Date Time.
Use DateTime.ParseExact with the format "MM/dd/yyyy HH:mm:ss"
startDate = DateTime.ParseExact(start,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
EDIT: based on comment from #John Woo
You can pass string array to DateTime.Parse like:
string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
dateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
use .ToString(CultureInfo.InvariantCulture) and Parse(value, CultureInfo.InvariantCulture) for values persistance. Only omit CultureInfo if you render values for display purpose. For some specific data formats special formatting rules may exist - follow them.
to recover your data use ParseExact.
As Habib already answered:
//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
It should help.

C# : Convert datetime from string with different format

If my string is 26/01/2011 00:14:00
but my computer set United state format (AM:PM)
How to convert my string into Datetime?
I try Convert.ToDateTime() but it cause error.
As the others have said, you can use DateTime.TryParseExact, but you also seem to have a European culture format in your date. It might not hurt to make an attempt to use that to perform the conversion:
CultureInfo enGB = new CultureInfo("en-GB");
string dateString;
DateTime dateValue;
// Parse date with no style flags.
dateString = "26/01/2011 00:14:00";
DateTime.TryParseExact(dateString, "g", enGB, DateTimeStyles.None, out dateValue);
Use DateTime.ParseExact or DateTime.TryParseExact. If you have to accept multiple possible datetime formats, both of those methods have overloads that take an array of format strings.
As far as that format, it looks like "dd/mm/yyyy HH:MM:ss"
I use DateTime.Tryparse - that way you can catch and handle a failure gracefully:
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

Categories