将文本格式化为日期/时间格式c#

本文关键字:时间 格式 日期 文本 格式化 | 更新日期: 2023-09-27 18:15:43

我创建了一个windows 8应用程序,它将有一个倒计时计时器。我有定时器的代码,它工作得很好,但不是从120秒倒数,我想要它显示为2:00分钟和倒计时从那里。但是因为我使用计时器,我不确定如何使用日期/时间属性(如果我能做到这一点)。请帮我弄明白。

这是我的定时器代码:

 DispatcherTimer timer;
 private int counter = 120;
 public ArcadeMode()
 {
     InitializeComponent();
     timer = new DispatcherTimer();
     timer.Interval = TimeSpan.FromSeconds(1);
     timer.Tick += timer_Tick;
     timer.Start();
  }
  async void timer_Tick(object sender, object e)
  {
     await Time.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { Time.Text = counter.ToString(); });
     counter--;
   }

将文本格式化为日期/时间格式c#

Time.Text = TimeSpan.FromSeconds(counter).ToString();

如果输入是60

则输出为00:01:00

也许有更快/更简洁的方法,但这至少应该以您想要的方式显示计时器(未经测试):

Time.Text = string.Format("{0}:{1}", (counter / 60), (counter % 60).ToString().PadLeft(2,'0'));

将其转换为Datetime实例和。tostring("您想要的格式")