C#DateTime.Parse(longdate)抛出异常

时间:2017-10-12 07:01:42

标签: c# datetime uwp

在UWP中,将日期格式化为longdate字符串,如此

string myDateString = new DateTimeFormatter("longdate").Format(DateTime.Today);

给出myDateString = "‎Thursday‎, ‎12‎ ‎October‎ ‎2017"

尝试将其转换回来

DateTime myDate = DateTime.Parse(myDateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);

抛出System.FormatException

尝试将其转换回来

DateTime myDate = DateTime.ParseExact(myDateString, "longdate", CultureInfo.CurrentCulture);

同时抛出System.FormatException

然后我将我的机器设置为美国。 myDateString = "‎Thursday‎, ‎October‎ 12‎ ‎‎2017"

的值

但是当我尝试将其转换回日期时间时,这也会引发System.FormatException

如何使用当前文化将长日期字符串转换为C#中的日期时间?

3 个答案:

答案 0 :(得分:0)

string sd = "‎Thursday‎,‎ ‎October‎ 12, ‎2017";
sd = DateTime.Now.ToString("dddd, MMMM dd, yyyy", new CultureInfo("en-US"));
DateTime myDate;
if (DateTime.TryParseExact(sd,"dddd, MMMM dd, yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out myDate))
{
   Console.WriteLine(myDate);    //if format accepted.
}

答案 1 :(得分:0)

@Jay Zuo在Cannot convert string to DateTime in uwp

中解释
  

当我们使用DateTimeFormatter.Format方法时,返回值中有一些不可见的8206个字符

正如@Corak建议的那样,不要使用DateTimeFormatter,请使用ToString("D")

答案 2 :(得分:-1)

阅读一些DateTime格式...... DateTime Formats

相关的帖子帖子:here

日期时间基础知识:basics

使用DateTime with culture

的示例

一个基本的例子:

DateTime d = DateTime.Now;
DateTime ut = d.ToUniversalTime();
// Defines a custom string format to display the DateTime value.
// zzzz specifies the full time zone offset.
  String format = "MM/dd/yyyy hh:mm:sszzz";

String utcstr = utcdt.ToString(format);
      Console.WriteLine(utcstr);

编辑:小型控制台应用示例

static void Main(string[] args)
        {
            string myDateString = "Thursday, 12 October 2017";
            //Why use the above just get a new one for today in the correct format
            //Or create your own converter
            DateTime date = DateTime.Now;

            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            //or
            var culture = System.Globalization.CultureInfo.CurrentCulture;

            string test = currentCulture.ToString();

             Console.WriteLine(date.ToString(CultureInfo.GetCultureInfo(test)));
            Console.ReadLine();
        }