[英]"String was not recognized as a valid DateTime." format "yyyy-MM-dd" how i can use this format
My script from txtdate;我的 txtdate 脚本;
<asp:TextBox ID="txtDate1" AutoComplete="off" runat="server" ></asp:TextBox>
<script type="text/javascript">
$(function () {
$('[id*=txtDate]').datepicker({
changeMonth: true,
changeYear: true,
format: "yyyy/MM/dd",
language: "tr"
});
});
</script>
I try to use format in my date time我尝试在我的日期时间使用格式
DateTime x = DateTime.ParseExact(txtDate1.Text, "yyyy-MM-dd", new CultureInfo("en-US")).AddDays(7);
I get an error:我收到一个错误:
String was not recognized as a valid DateTime
字符串未被识别为有效的日期时间
But this format works:但这种格式有效:
DateTime x = DateTime.ParseExact(txtDate1.Text, "dd/MM/yyyy", new CultureInfo("en-US")).AddDays(7);
How can I use format "yyyy-MM-dd" ?如何使用格式“yyyy-MM-dd”?
In your JS it looks like you expecting string that contains date in this format format: "yyyy/MM/dd
So both of your parsing should be invalid.在您的 JS 中,您似乎期望包含此格式
format: "yyyy/MM/dd
日期的字符串format: "yyyy/MM/dd
所以您的两个解析都应该是无效的。
So how this DateTime.ParseExact works:那么这个DateTime.ParseExact是如何工作的:
You have input string that can be formatted in different ways.您有可以以不同方式格式化的输入字符串。
DateTime.ParseExact is defined: DateTime.ParseExact定义为:
public static DateTime ParseExact (string s, string format, IFormatProvider? provider);
docs: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-5.0文档: https : //docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact? view = net- 5.0
So example:所以例子:
var dateString = "11/04/2021";
If you do:如果你这样做:
var date = DateTime.ParseExact(dateString, "dd/MM/yyyy", new CultureInfo("en-US"));
Your date
will be 11th April 2021
您的
date
将是11th April 2021
But if you do:但如果你这样做:
var date = DateTime.ParseExact(dateString, "MM/dd/yyyy", new CultureInfo("en-US"));
Your date
will be 4th November 2021
您的
date
将是4th November 2021
Addition:添加:
If you try this:如果你试试这个:
var date = DateTime.ParseExact(dateString, "MM-dd-yyyy", new CultureInfo("en-US"));
You will be thrown System.FormatException: "String was not recognized as a valid DateTime."
您将被抛出
System.FormatException: "String was not recognized as a valid DateTime."
simply because string is "11/04/2021" and you telling your parser to expect "MM-dd-yyyy" Hope its clearer now.仅仅因为字符串是“11/04/2021” ,你告诉你的解析器期待“MM-dd-yyyy”希望现在更清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.