如何在 blazor 服务器应用程序组件中使用时间跨度并转换为 12 小时格式

how to use timespan in the component of blazor server app and convert to 12 hour format

My requirements are to add timeslot settings , edit and show that timeslots fields from the database are : 1.ID(short) 2.FromTime (TimeSpan) 3.ToTime(TimeSpan) 4.DisplayTime(string)

Model CLass:

        public short TimeSlotID { get; set; }
        public TimeSpan FromTime { get; set; }
  

      public TimeSpan ToTime { get; set; }

Database Read:

 yield return new TimeSlotModel
                    {
                        TimeSlotID = reader.GetInt16("TimeSlotID"),
                        FromTime = (TimeSpan)reader["FromTime"],
                        ToTime = (TimeSpan)reader["ToTime"],
                   
                        DisplayText = reader.SafeGetString("DisplayText"),
};

Razor page

 <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; }
}