[英]String was not recognized as a valid DateTime. Throws an Exception
I'm trying to convert current date to a specified format. 我正在尝试将当前日期转换为指定的格式。
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I'm receiving the following exception. 我收到以下异常。
String was not recognized as a valid DateTime.
无法将字符串识别为有效的DateTime。
My local TimeZone is (UTC+10:00)Melbourne. 我当地的时区是(UTC + 10:00)墨尔本。
What am I doing wrong here? 我在这里做错了什么?
Your code (even if it worked), would do nothing. 您的代码(即使有效)也无济于事。 It would simply serialize and deserialize the date.
它将简单地序列化和反序列化日期。 I believe you're looking for this:
我相信您正在寻找这个:
string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
It doesn't work because DateTime.Now.ToString()
is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you): 这是行不通的,因为
DateTime.Now.ToString()
给出了这样的字符串(我恰好在同一时区,并且大概与您具有相同的文化):
14/01/2016 3:54:01 PM
Which is of the format: 格式如下:
dd/MM/yyyy h:mm:ss tt
Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff
哪种格式与您使用的格式不匹配:
yyyy-MM-dd HH:mm:ss.fff
Try this: 尝试这个:
string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);
EDIT: 编辑:
A better way to achieve the date in the format would be like 达到日期格式的更好方法是
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.