我正在尝试在以下模型中手动将字符串设置为有效的DateTime:
namespace Application.Models
{
public class Tienda
{
...
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime tienda_fecha_fin { get; set; }
...
通过控制器:
[HttpPost, ActionName("Create")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(int? id, StoreIndexData AddStore)
{
if (ModelState.IsValid)
{
var store = new Tienda();
store.tienda_fecha_fin = DateTime.ParseExact("31/12/9999 12:00:00", "0:dd/MM/yyyy", CultureInfo.InvariantCulture);
由于我不记得0:dd/MM/yyyy
期望的确切格式,因此我尝试了不同的方法。
我尝试过:
31/12/9999; 31/12/9999 12:00:00 AM; 31/12/9999 12:00:00
到目前为止没有运气
答案 0 :(得分:1)
在调用DateTime.ParseExact时,删除format参数的0:
部分。那是调用string.Format
方法时在字符串模板中使用的占位符。
您要:
DateTime.ParseExact("31/12/9999", "dd/MM/yyyy", CultureInfo.InvariantCulture);
答案 1 :(得分:1)
您正在尝试将“ 31/12/9999 12:00:00”解析为“ dd / MM / yyyy”
您应该使用:
DateTime.ParseExact("31/12/9999", "dd/MM/yyyy", CultureInfo.InvariantCulture);
或
DateTime.ParseExact("31/12/9999 12:00:00", "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);