I am trying to set the live DateTime in blazor webpages. I tried using Datetime.now . it's not updating the live time. I want to do it without using javascript.
Any help regarding this issue?
I am trying to set the live DateTime in blazor webpages. I tried using Datetime.now . it's not updating the live time. I want to do it without using javascript.
Any help regarding this issue?
You need a Timer. Shortest sample I could think of:
@page "/"
@using System.Threading
@implements IDisposable
<p>@theTime</p>
@code{
string theTime;
Timer aTimer;
protected override void OnInitialized()
{
aTimer = new Timer(Tick, null, 0, 1000);
}
private void Tick(object _)
{
theTime = DateTime.Now.ToLongTimeString();
InvokeAsync(StateHasChanged);
}
public void Dispose()
{
aTimer?.Dispose();
}
}
Similar one, using "System.Timers"
@page "/digitalclock"
@using System.Timers
@implements IDisposable
<PageTitle>Digital Clock</PageTitle>
<h1>@currentTime</h1>
@code {
private string currentTime = DateTime.Now.ToString("HH:mm:ss tt");
private Timer? secondsTimer;
protected override void OnInitialized()
{
//one second interval
secondsTimer = new Timer(1000);
secondsTimer.Enabled = true;
secondsTimer.AutoReset = true;
secondsTimer.Elapsed += (sender, e) => UpdateTime();
}
private void UpdateTime()
{
currentTime = DateTime.Now.ToString("HH:mm:ss tt");
InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
secondsTimer?.Dispose();
}
}