【发布时间】:2021-05-03 07:43:39
【问题描述】:
我有一个数据库来存储新书进入系统的日期时间。在 Xamarin.Forms 中,我希望以 HH:MM:SS 显示自数据库中最近的 DateTime 以来的时差。
目前,标签显示时差 (HH:MM:SS:MS),但不会增加。没有新书进入时,显示的时间差每增加一秒。
我正在考虑使用循环每秒调用CalculateTimeDifference() 函数,但我想知道是否有更有效的解决方案。
MainPage.xaml:
<StackLayout Orientation="Horizontal" HorizontalOptions="Center">
<Label x:Name="labelTimeSince" Text="00:00:00" VerticalOptions="Center"/>
<Button Text="Add New" x:Name="BtnAdd" Clicked="BtnAdd_Clicked"></Button>
</StackLayout>
MainPage.cs:
protected override void OnAppearing()
{
base.OnAppearing();
CalculateTimeDifference();
}
void BtnAdd_Clicked(object sender, EventArgs e)
{
Book book = new Book
{
BookSaveTime = DateTime.Now
};
App.Database.SaveBook(book);
CalculateTimeDifference();
}
void CalculateTimeDifference()
{
var latestBook = App.Database.GetRecentBookDate().FirstOrDefault();
var timeDifference = DateTime.Now - latestBook.BookSaveTime;
this.labelTimeSince.Text = timeDifference.ToString();
}
数据库.cs:
public int SaveBook(Book book)
{
return database.Insert(book);
}
public List<Book> GetRecentBookDate()
{
return database.Query<Book>("SELECT * FROM Book ORDER BY BookSaveTime DESC LIMIT 1;");
}
Book.cs:
public class Book: INotifyPropertyChanged
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
private DateTime bookSaveTime;
public DateTime BookSaveTime
{
get
{
return bookSaveTime;
}
set
{
if (bookSaveTime != value)
{
bookSaveTime= value;
OnPropertyChanged("BookSaveTime");
}
}
}
}
我怎样才能做到以下几点:
- 格式化时间差的显示方式(HH:MM:SS - 没有毫秒)。
- 在没有存储新书的情况下,每秒持续增加一秒的时间差
【问题讨论】:
-
您的应用是单用户还是多用户?
-
@Miamy 是单用户。
-
使用 System.Timers.Timer,而不是连续循环。每秒触发一次计时器并更新您的 UI。在 C# 中格式化日期时间字符串已被广泛记录
标签: c# sqlite datetime xamarin xamarin.forms