如何解决如何在 blazor 服务器应用程序的组件中使用时间跨度并转换为 12 小时格式
我的要求是添加时间段设置,编辑和显示时间段 数据库中的字段是: 1.ID(短) 2.FromTime(时间跨度) 3.ToTime(时间跨度) 4.DisplayTime(字符串)
模型类:
public short TimeSlotID { get; set; }
public TimeSpan FromTime { get; set; }
public TimeSpan ToTime { get; set; }
数据库读取:
yield return new TimeSlotModel
{
TimeSlotID = reader.GetInt16("TimeSlotID"),FromTime = (TimeSpan)reader["FromTime"],ToTime = (TimeSpan)reader["ToTime"],DisplayText = reader.SafeGetString("DisplayText"),};
剃刀页面
<div class="row">
<div class="col">
<label for="TimeSlotID">TimeSlotID</label>
</div>
</div>
<div class="row">
<div class="col-4">
<label for="FromTime">FromTime</label>
</div>
<div class="col">
<label for="ToTime">ToTime</label>
</div>
</div>
<div class="form-group">
<div class="col">
<label for="DisplayText">DisplayText</label>
@item.DisplayText
</div>
</div>
I found it difficult to use any components to read and add or edit coz its Timespan .
i used datetimepicker but i dont know how to convert that to timespan while saving that to the database.Can anyone help solve this one.
谢谢!
解决方法
此解决方案绑定到用于设置模型时间跨度的 DateTimeOffset 属性。
Index.razor
@page "/"
<input type="time" @bind-value="FromTime" />
<input type="time" @bind-value="ToTime" />
<hr />
@ConvertTo12HourFormat(SomeModel.FromTime) - @ConvertTo12HourFormat(SomeModel.ToTime)
Index.razor.cs
using System;
using Microsoft.AspNetCore.Components;
public partial class Index : ComponentBase
{
readonly DateTimeOffset aDate = new DateTime(2020,01,01);
public SomeModel SomeModel { get; set; } = new SomeModel();
public DateTimeOffset FromTime
{
get { return aDate.Add(SomeModel.FromTime); }
set { SomeModel.FromTime = value.Subtract(aDate); }
}
public DateTimeOffset ToTime
{
get { return aDate.Add(SomeModel.ToTime); }
set { SomeModel.ToTime = value.Subtract(aDate); }
}
public string ConvertTo12HourFormat(TimeSpan time) => aDate.Add(time).ToString("hh:mm:ss tt");
}
SomeModel.cs
public class SomeModel
{
public short TimeSlotID { get; set; }
public TimeSpan FromTime { get; set; }
public TimeSpan ToTime { get; set; }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。