
< /p>
Но само приложение показывает старое время, а значение переменных isDaylightSaving остается прежним. Если я перезапущу приложение, потребуется правильное время.
Но как получить правильное время при смене DLS без перезапуска?
public partial class Form1 : Form
{
private Label lblDateTime;
private System.Windows.Forms.Timer timer;
private TimeZoneInfo localTimeZone;
public Form1()
{
InitializeComponent();
// Initialize the form and label
this.Text = "Day Time Information";
this.Width = 400;
this.Height = 200;
lblDateTime = new Label();
lblDateTime.Font = new System.Drawing.Font("Arial", 16);
lblDateTime.Location = new System.Drawing.Point(50, 50);
lblDateTime.AutoSize = true;
this.Controls.Add(lblDateTime);
// Get local time zone
localTimeZone = TimeZoneInfo.Local;
// Initialize the timer
timer = new System.Windows.Forms.Timer();
timer.Interval = 1000; // Set interval to 1000 ms = 1 second
timer.Tick += Timer_Tick;
timer.Start(); // Start the timer
// Update the label immediately when form loads
UpdateDateTime();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Timer_Tick(object sender, EventArgs e)
{
UpdateDateTime(); // Update label every tick (1 second)
}
private void UpdateDateTime()
{
// Get current UTC time
DateTimeOffset utcNow = DateTimeOffset.UtcNow;
// Calculate the local time by applying the local time zone offset, considering DST
DateTimeOffset localTime = TimeZoneInfo.ConvertTime(utcNow, localTimeZone);
// Check if the time is currently in Daylight Saving Time in the local time zone
bool isDaylightSaving = localTimeZone.IsDaylightSavingTime(localTime);
// Display the local time with DST status
lblDateTime.Text = $"{localTime:dddd, MMMM dd, yyyy h:mm:ss tt} (DST: {isDaylightSaving})";
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... e-and-time
Мобильная версия