将日期时间转换为日期:Post 方法显示失败
Posted
技术标签:
【中文标题】将日期时间转换为日期:Post 方法显示失败【英文标题】:Convert date time into date:Post method showing failed 【发布时间】:2020-06-28 15:38:15 【问题描述】:我是 react 和 web api 开发的新手。我遇到了日期时间问题。因为我的员工模型中有一个日期时间组件。
代码在这里:
Employee.cs
namespace WebAPI.Models
public class Employee
public long EmployeeID get; set;
public string EmployeeName get; set;
public string Department get; set;
public string MailID get; set;
public DateTime DOJ get; set;
我正在尝试使用员工控制器将模式弹出窗口中的元素添加到我的数据库中。但是,我认为由于弹出窗口接受日期和 web api 通过日期时间而失败。因此插入时存在不匹配。我尝试通过将此代码添加到员工控制器来解决此问题。
string doj = emp.DOJ.ToString().Split(' ')[0];
这是我的员工控制器部分:
public string Post(Employee emp)
try
DataTable table = new DataTable();
string doj = emp.DOJ.ToString().Split(' ')[0];
string query = @"
insert into dbo.Employees
(EmployeeName,
Department,
MailID,
DOJ)
Values
(
'" + emp.EmployeeName + @"',
'" + emp.Department + @"',
'" + emp.MailID + @"',
'" + doj + @"'
)
";
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeAppDB"].ConnectionString))
using (var cmd = new SqlCommand(query, con))
using (var da = new SqlDataAdapter(cmd))
cmd.CommandType = CommandType.Text;
da.Fill(table);
return "Added Successfully";
catch (Exception )
return "Failed to Add";
这是我在 Visual Studio 代码中使用的代码:
class AddEmpModal extends Component
constructor(props)
super(props);
this.state = deps:[],sanackbaropen: false, snackbarmsg:'';
this.handleSubmit = this.handleSubmit.bind(this);
componentDidMount()
fetch('https://localhost:44363/api/department')
.then(response=> response.json())
.then(data=>
this.setState(deps:data);
);
snackbarClose = (event) =>
this.setState(snackbaropen:false);
;
handleSubmit(event)
event.preventDefault();
fetch('https://localhost:44363/api/Employee',
method:'POST',
headers:
'Accept':'application/json',
'Content-Type':'application/json'
,
body:JSON.stringify(
EmployeeID:null,
EmployeeName: event.target.EmployeeName.value,
Department: event.target.Department.value,
MailID: event.target.MailID.value,
DOJ: event.target.DOJ.value,
)
)
.then(res=> res.json())
.then((result)=>
//alert(result);
this.setState(snackbaropen:true,snackbarmsg:result)
,
(error)=>
// alert('Failed')
this.setState(snackbaropen:true,snackbarmsg:'failed')
)
您能否告诉我解决日期时间问题的方法或告诉我哪里出错了?
【问题讨论】:
【参考方案1】:我认为问题在于您的 webapi 和数据库之间。我不会将来自 react-application 的 datetime-string 更改为 doj 变量。但是,我会检查您的 webapi 中的查询字符串,并可能将原始 emp.DOJ 变量转换为标准格式。
例如,如果您使用 microsoft sql server,则插入语句将包含以下日期:
convert(datetime, emp.DOJ, datetime-format-code)
代替:
doj
请参阅this list 了解所有受支持的日期时间格式代码。
【讨论】:
所以不是 web api 中的 doj,你想让我将 convert 变量添加到提到 doj 的行吗? 我会在您的插入语句中将 doj 更改为 emp.DOJ 并将其包装在转换函数中。因此,如果您的 react 日期格式看起来像 dd-mm-yyyy 00:00:00 您的 doj insert 语句必须如下所示: convert(datetime,' "+ emp.DOJ + @" ' ,105) 我认为您的其余代码看起来不错。您只需在插入语句中更改该行。如果有效,请告诉我... 我试过上面的代码。它不接受convert(datetime,' "+ emp.DOJ + @" ',105)以上是关于将日期时间转换为日期:Post 方法显示失败的主要内容,如果未能解决你的问题,请参考以下文章