简体   繁体   中英

C# date time try parse not parse valid date time

In C# when I pass a date examples like. mm/dd/yyyy...

It shows these results after parse

 // Example 1
 DateTime t = new DateTime();
 DateTime.TryParse("02/06/2013 00:00:00 PM", out t)

 // Example 2
 DateTime t = new DateTime();
 DateTime.TryParse("02/06/2013 00:00:10 PM", out t)

 // Example 3
 DateTime t = new DateTime();
 DateTime.TryParse("02/06/2013 00:10:10 PM", out t)

results are

2/6/2013 12:00:00 PM
2/6/2013 12:00:10 PM
2/6/2013 12:10:10 PM

Which shows incorrect dates while passing the date in sql server. How to resolve these type or issues. If these type of dates are invalid.

如果您可以将日期格式设置为yyyy-MM-dd ,则效果会更好-否则,您可能会遇到与语言环境相关的问题

You can use DateTime.TryParseExact to parse a specific format, regardless of culture. I believe you need dd-MM-yyyy HH:mm:ss PM.

Can use DateTime.ParseExact or DateTime.TryParseExact

For eg.

    string dateString = "Mon 16 Jun 8:30 AM 2008"; //Valid
    string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
{
    Console.WriteLine(dateTime); // 6/16/2008 8:30:00 AM 
}

Parse DateTime for UTC

DateTime.ParseExact(inputDate, "yyyy-MM-ddTHH:mm:ss.0000000Z", null).ToUniversalTime();

Parse DateTime with Format M/d/yyyy

DateTime.ParseExact(inputDate, "M/d/yyyy h:mm", CultureInfo.InvariantCulture);

The parses you exhibit seem alright. They do depend heavily on the current culture of the current thread. Specify CultureInfo.InvariantCulture as format provider in the TryParse call if you don't like that.

Your question about a SQL server is unclear. What SQL software, and what locale settings does that server have? How do you communicate with it?

Once you have your DateTime value t , you can format it in many ways. For example you can use

t.ToString("O")

to get a "big-endian" string with full precision. See Standard Date and Time Format Strings and Custom Date and Time Format Strings .

PS! You don't have to assign t when you declare it (when it is going to be used for an out argument).

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