C# : Convert datetime from string with different format - c#

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

Related

How to convert to system datetime format from a string?

I need to convert a string datetime format to a DateTime field which should be in system Datetime format?
I've tried Convert.ToDateTime, DateTime.Parse, DateTime.ParseExact but all of them convert to dd-MM-yyyy HH:mm:ss format.
My string is in yyyy-MM-dd HH:mm format.
I was trying TryParseExact and specifying the culture also but I just couldn't understand that how it works. Below is the code that I am trying and my item.CreationDate is in "yyyy-MM-dd HH:mm" format
DateTime dateTime;
bool isSuccess1 = DateTime.TryParseExact(item.CreationDate, "yyyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime);
DateTime result = dateTime;
Thanks in advance.
Can it be this easy? - yyyyy-MM-dd HH:mm has 5 ys in your example, not 4.
When you convert a string to DateTime you must state what format the input is in (as you have). If the conversion succeeded the DateTime object will hold the data for all the date parts (years, months, days etc.) and if you want to view them as a date again you must state what format you want to see them in. When using DateTime.TryParseExact it's worth noting that if the conversion fails it will set the value to the DateTime.MinValue.
There are various ways of showing the date again. The most common is stating the custom format for the date as a string. Another way is to use a standard format.
var creationDate = "2020-04-13 13:23";
DateTime.TryParseExact(creationDate, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateTime);
var myCulture = new CultureInfo("en-GB");
if(dateTime > DateTime.MinValue)
{
Console.WriteLine("Your custom format date is: " + dateTime.ToString("yyyy-MM-dd HH:mm"));
Console.WriteLine("Your standard format date is: " + dateTime.ToString("g", myCulture));
}
When you put this into a console app the results are like this:
With some of the standard format ones you will need to define the culture as it will be different for something like the en-US compared to something like zh-CN. In my case I used 'en-GB'. Here's a list of the accepted culture codes.

How to deal with dateformat that is from the Excel File and to convert it into MM/DD/YYYY using C#?

I have Date that comes in Excel File.
So far the requirement is, it can come in the Format as YYYY-MM-DD.
So I wrote the following code to convert it into MM/dd/yyyy:
DateTime excelDate = DateTime.ParseExact(value,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
value = value != "" ? excelDate.ToString("MM/dd/yyyy") : value;
But now the requirement is : it can come in any format as YYYY-MM-DD or MM/DD/YYYY or YYYYMMDD or MM-DD-YY.
Wonderin ghow to deal with these in a short way and convert that into MM/DD/YYYY ?
There is an overload to ParseExact that takes and array of format strings.
var formats = new string[] {"yyyy-MM-dd", "MM/dd/yyyy", "yyyyMMdd", "MM-dd-yy"};
DateTime excelDate = DateTime.ParseExact(value,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
If you don't know in advance exactly what formats might be coming in, DateTime.Parse() will attempt to detect the incoming format for you:
DateTime excelDate = DateTime.Parse(value
CultureInfo.InvariantCulture);
Note that you can also pass a DateTimeStyles parameter, but may not want or need to, depending on the behavior you want.
See http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx for details.

splitting string to array to create dateTime in c#

I have a string called TheUserTime that looks like this:
string TheUserTime = "12.12.2011.16.22"; //16 is the hour in 24-hour format and 22 is the minutes
I want to generate a DateTime from this by splitting the string in a array of ints (what happens when it's 0?) and composing the date object.
What's the best way to do this?
Thanks.
You should use DateTime.ParseExact or DateTime.TryParseExact with a custom format string instead.
ParseExact:
DateTime.ParseExact("12.12.2011.16.22", "dd.MM.yyyy.HH.mm",
CultureInfo.InvariantCulture)
TryParseExact:
DateTime dt;
if(DateTime.TryParseExact("12.12.2011.16.22", "dd.MM.yyyy.HH.mm",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out dt))
{
// parse successful use dt
}
Using TryParseExact avoids a possible exception if the parse fails, though is such a case the dt variable will have the default value for DateTime.
I would not recommend your approach, but instead use ParseExact and specify the expected format.
string theUserTime = "12.12.2011.16.22";
var date = DateTime.ParseExact(theUserTime, "MM.dd.yyyy.HH.mm", CultureInfo.CurrentCulture);
You can use:
DateTime.ParseExact("12.12.2011.16.22", "MM.dd.yyyy.HH.mm", System.Globalization.CultureInfo.InvariantCulture);

Unable to parse DateTime from a string

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

String to datetime

I have a string 12012009 input by the user in ASP.NET MVC application. I wanted to convert this to a DateTime.
But if I do DateTime.TryParse("12012009", out outDateTime); it returns a false.
So I tried to convert 12012009 to 12/01/2009 and then do
DateTime.TryParse("12/01/2009", out outDateTime); which will work
But I don't find any straight forward method to convert string 12012009 to string "12/01/2009". Any ideas?
First, you need to decide if your input is in day-month-year or month-day-year format.
Then you can use DateTime.TryParseExact and explicitly specify the format of the input string:
DateTime.TryParseExact("12012009",
"ddMMyyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out convertedDate)
See also: Custom Date and Time Format Strings
You can use the DateTime.TryParseExact and pass in the exact format string:
DateTime dateValue = DateTime.Now;
if (DateTime.TryParseExact("12012009", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)))
{
// Date now in dateValue
}
If you want to use that format you will most likely need to specify the format to the parser. Check the System.IFormatProvider documentation as well as the System.DateTime documentation for methods that take an IFormatProvider.
DateTime yourDate =
DateTime.ParseExact(yourString, "ddMMyyyy", Culture.InvariantCulture);

Categories