splitting string to array to create dateTime in c# - 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);

Related

converting a string to a DateTime format

I'm trying to parse 09/01/2015 00:00:00 to the format yyyy-MM-ddThh:mm:ssZ using following method:
DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);
But I'm getting String was not recognized as a valid DateTime
Can anyone tell me why? I believe 09/01/2015 00:00:00 is a valid DateTime format?
From DateTime.ParseExact
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 are not.
I assume your 09 part is day numbers, you can use dd/MM/yyyy HH:mm:ss format instead.
var dt = DateTime.ParseExact("09/01/2015 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Since CultureInfo already implements IFormatProvider, you don't need to explicitly cast it.
I don't understand this. So it means I first have to correct my string
and secondly I can do a ParseExact(). I thought ParseExact could
handle the given string...
ParseExact is not a magical method that can parse any formatted string you suplied. It can handle only if your string and format perfectly matches based on culture settings you used.
Try this code:
var text = "09/01/2015 00:00:00";
var format = "dd/MM/yyyy HH:mm:ss";
var dt = DateTime.ParseExact(text, format, (IFormatProvider)CultureInfo.InvariantCulture);
You'll notice that the format must structurally match the text you're trying to parse exactly - hence the ParseExact name for the method.
The format does not match, you need to change 09/01/2015 into 2015-01-09 or theyyyy-MM-dd part into dd/MM/yyyy.
The ParseExact-method is no ultimate method that converts ANY dateformat into another one, it is simply to parse a given string into a datetime using the provided format. Thus if your inout does not match this format the method will throw that exception.
As a datetime is internally only a number there is no need to convert one format into another at all, so as long as you know your input-format you can build a date from it which has nothing to do with any formatting which you may need when you want to print that date to your output. In this case you WILL need a formatter.
As most people have stated the error is coming from the fact that the date in string format doesn't match the format you are saying it's in. You are saying that 09/01/2015 00:00:00 is in the format "yyyy-MM-ddThh:mm:ssZ", which it's not, hence the error. To rectify this you need to either alter the format the string is in, or more likely, change the format you are saying the date is in. So change "yyyy-MM-ddThh:mm:ssZ" to "dd/MM/yyyy HH:mm:ss".
In a more long term view how are you arriving at that date? Is it possible that the format may change (input but the user)? If so it might be better to try and avoid the error being thrown and handle it better with TryParseExact. To make use of this best I generally output a nullable DateTime and then check if it's null. If you don't do this then if the parse fails it will simply make the output datetime the minimum value.
Something like this should work:
public DateTime? StringToDate (string dateString, string dateFormat)
{
DateTime? dt;
DateTime.TryParseExact(dateString, dateFormat, null, System.Globalization.DateTimeStyles.None, out dt);
return dt;
}
Then you can use it like this:
DateTime? MyDateTime = StringToDate("09/01/2015 00:00:00", "dd/MM/yyyy HH:mm:ss");
if(MyDateTime != null)
{
//do something
}
Another simple way to do this...
var dt = Convert.ToDateTime(Convert.ToDateTime("09/01/2015 00:00:00").ToString("yyyy-MM-ddThh:mm:ssZ"))

C# Datetime format conversion

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

Convert YYYYMMDD string to MM/DD/YYYY string

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);
However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.
DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
Then your code will work.
Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.
You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

C#: How to convert string to date accordingly to the giver format?

I have 2 strings: one is date value like "20101127", the second is format "yyyymmdd". How could I extract the date from the value using the given format?
Thanks
Use DateTime.ParseExact:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", null);
null will use the current culture, which is somewhat dangerous. You can also supply a specific culture, for example:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", CultureInfo.InvariantCulture);
Use DateTime.ParseExact(). Note that month is MM, not mm.
var dateValue = DateTime.ParseExact("20101127", "yyyyMMdd",
CultureInfo.InvariantCulture);
Use the ParseExact method.

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