简体   繁体   English

将字符串转换为DateTime和格式

[英]Convert string to DateTime and format

Can i convert the string below to DateTime 我可以将下面的字符串转换为DateTime

Friday, 27th September 2013 2013年9月27日星期五

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. 该字符串未被识别为有效的DateTime。 There is an unknown word starting at index 10. 从索引10开始有一个未知单词。

Well, I'm not sure there is exactly solution with -th, -st, -nd , but you can use this like; 好吧,我不确定是否有-th, -st, -nd确切解决方案,但你可以使用它;

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

Here a DEMO . 这是一个DEMO

I almost suggest you remove -th , -st and -nd part of your string but these are break the rules :) 我几乎建议你删除-th-st-nd你的字符串的一部分,但这些都是破坏规则:)

  • August 八月
  • Monday 星期一
  • Thursday 星期四
  • Sunday 星期日

Also check Habib's answer which seems nice. 还要检查Habib的答案 ,这看起来不错。

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. 如果无法从字符串中解析DateTime则使用TryParseExact可以避免抛出异常。

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. 显然,这里不需要“th”。 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. 你必须手动删除th,nd,rd和st,因为没有任何格式考虑到这些。 After that you can use try parse exact like below 之后,您可以使用下面的try解析

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). 假设您提供的日期字符串的格式不会更改,则可以轻松删除-st,-nd和-th(如已建议的那样)。

Also be sure to provide a valid (existing) date, or a System.FormatException will be thrown. 还要确保提供有效(现有)日期,否则将抛出System.FormatException。

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 请参阅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);
  }                              
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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