代码之家  ›  专栏  ›  技术社区  ›  MrM

把数字转换成时间?

  •  7
  • MrM  · 技术社区  · 14 年前

    有没有一种巧妙的方法将简单的数字(包括陆军时间)转换成时间格式(am、pm格式)?我可以用这种枯燥的方法,但我只是想知道是否还有别的方法

    0800=>上午8:00

    3 回复  |  直到 14 年前
        1
  •  14
  •   Brian    14 年前
        DateTime dt = DateTime.ParseExact("0800", "HHmm", CultureInfo.InvariantCulture);
        string timestring = dt.ToString("h:mm tt");
    

    看到了吗 documentation 格式代码。

        2
  •  1
  •   Robaticus    14 年前

        string time = "0800";
        DateTime dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture);
        MessageBox.Show(string.Format("{0:h:mm tt}", dt));
    
        time = "2345";
        dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture);
        MessageBox.Show(string.Format("{0:h:mm tt}", dt));
    
        3
  •  1
  •   ChrisF toni    14 年前

    使用 DateTime.TryParse 使用所需的格式字符串。