英文:
Issue parsing DateTime
问题
我有以下字符串 2023-07-18 11:38 AM
我尝试使用以下代码解析它
fromDate = DateTime.ParseExact(adhocData.FromDateTime,
"yyyy-MM-dd hh:mm tt",
CultureInfo.InvariantCulture).Date;
但我一直收到以下错误
字符串 '2023-07-18 11:38 AM' 未被识别为有效的 DateTime
英文:
I have the following string 2023-07-18 11:38 AM
I'm trying to parse it using the following code to parse the same
fromDate = DateTime.ParseExact(adhocData.FromDateTime,
"YYYY-MM-DD hh:mm tt",
CultureInfo.InvariantCulture).Date;
But i keep getting the following error
> String '2023-07-18 11:38 AM' was not recognized as a valid DateTime
答案1
得分: 3
你的格式略有错误,请尝试:
DateTime.ParseExact("2023-07-18 11:38 AM",
"yyyy-MM-dd hh:mm tt",
CultureInfo.InvariantCulture);
注意年份和日期组件的大写!
英文:
Your format is slightly wrong, try:
DateTime.ParseExact("2023-07-18 11:38 AM",
"yyyy-MM-dd hh:mm tt",
CultureInfo.InvariantCulture);
Note the caps of the year and day component!
答案2
得分: 3
使用字符串格式"yyyy-MM-dd hh:mm tt"而不是"YYYY-MM-DD hh:mm tt"。
这修复了问题,甚至时间显示正常。
英文:
Use the string format "yyyy-MM-dd hh:mm tt" instead of "YYYY-MM-DD hh:mm tt".
This fixed the problem and even the time is displaying properly.
答案3
得分: 1
A better option would be to ensure ISO8601 is sent from the client. From the comments, the string is generated in a React application using moment with apiFromDateTime?.format('YYYY-MM-DD hh:mm a')
. There's no need for this.
moment
objects are serialized to ISO8601 out of the box though. The documentation example shows how an object containing a moment
object gets serialized to JSON:
{'postDate':'2013-02-04T22:44:30.652Z'}
POSTing this to the server with fetch
should just work. Borrowing MDN's fetch example:
const data={
postDate : moment()
}
const response = await fetch("https://example.com/profile", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
英文:
A better option would be to ensure ISO8601 is sent from the client. From the comments, the string is generated in a React application using moment with apiFromDateTime?.format('YYYY-MM-DD hh:mm a')
. There's no need for this.
moment
objects are serialized to ISO8601 out of the box though. The documentation example shows how an object containing a moment
object gets serialized to JSON:
JSON.stringify({
postDate : moment()
});
This produces
'{"postDate":"2013-02-04T22:44:30.652Z"}'
POSTing this to the server with fetch
should just work. Borrowing MDN's fetch example :
const data={
postDate : moment()
}
const response = await fetch("https://example.com/profile", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论