简体   繁体   中英

Convert string to DateTime and format

Can i convert the string below to DateTime

Friday, 27th September 2013

This is what i want to achieve:

String tmpDate="Friday, 27th September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");

Doing above i get error:

The string was not recognized as a valid DateTime. There is an unknown word starting at index 10.

Well, I'm not sure there is exactly solution with -th, -st, -nd , but you can use this like;

string tmpDate = "Friday, 27 September 2013";
DateTime dt = DateTime.ParseExact(tmpDate,
                                  "dddd, dd MMMM yyyy",
                                  CultureInfo.InvariantCulture);

Here a DEMO .

I almost suggest you remove -th , -st and -nd part of your string but these are break the rules :)

  • August
  • Monday
  • Thursday
  • Sunday

Also check Habib's answer which seems nice.

You can maintain the ordinals to remove in an array like this (which might make it easier to add/remove ordinals from other languages). That way you don't have to manually remove the ordinal from each string input. Using TryParseExact avoids an exception being thrown if the DateTime could not be parsed from the string.

String tmpDate = "Friday, 27th September 2013";
string[] split = tmpDate.Split();
string[] ordinals = new string[] { "th", "nd", "st" };

foreach (string ord in ordinals)
   split[1] = split[1].Replace(ord, "");

tmpDate = String.Join(" ", split);
DateTime dt;
if(DateTime.TryParseExact(tmpDate, "dddd, dd MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   Console.WriteLine("Parsed");
}
else
{
   Console.WriteLine("Could not parse");
}

Your answer is in the exception you are getting. Obviously, "th" is not needed here. Just remove it and you are good to go.

This is working perfectly fine for me

String tmpDate = "Friday, 27 September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");

you will have to remove the th, nd,rd and st manually, as there isn't any format that takes these into account. After that you can use try parse exact like below

String tmpDate = "Friday, 27th September 2013";
tmpDate = tmpDate.Replace("nd", "")
            .Replace("th", "")
            .Replace("rd", "")
            .Replace("st", "");            
string[] formats = { "dddd, dd MMMM yyyy" };
DateTime dt;
if (DateTime.TryParseExact(tmpDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dt))
{
     //parsing is successful
}

Assuming the format of the date string you provide does not change, the -st, -nd and -th can easily be removed (as already suggested).

Also be sure to provide a valid (existing) date, or a System.FormatException will be thrown.

string tmpDate = "Friday, 27th September 2013";

string[] splitDate = tmpDate.Split(new Char[] {' '});
splitDate[1] = splitDate[1].Substring(0, splitDate[1].Length-2);
string tmpDatewithoutStNdTh = String.Join(" ", splitDate);

try{
    string closingDate = Convert.ToDateTime(tmpDatewithoutStNdTh).ToString("yyyy-MM-dd");
    Console.WriteLine(closingDate.ToString());
}
catch(System.FormatException)
{
    Console.WriteLine("The provided date does not exist.");
}

See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx

public class Example
{
public static void Main()
{
  string[] dateStrings = {"2008-05-01T07:34:42-5:00", 
                          "2008-05-01 7:34:42Z", 
                          "Thu, 01 May 2008 07:34:42 GMT"};
  foreach (string dateString in dateStrings)
  {
     DateTime convertedDate = DateTime.Parse(dateString);
     Console.WriteLine("Converted {0} to {1} time {2}", 
                       dateString, 
                       convertedDate.Kind.ToString(), 
                       convertedDate);
  }                              
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM