我正在使用这些代码在VB.NET中显示时间 它以24小时格式显示,除了我需要12小时格式
System.DateTime.Now.Hour
System.DateTime.Now.Minute
System.DateTime.Now.Second
示例:
14:12:42
我需要它:
02:12:42
感谢。
答案 0 :(得分:3)
使用String.Format。例如:
String.Format("{0:T}", System.DateTime.Now) //02:12:42 PM
String.Format("{0:hh:mm:ss}", System.DateTime.Now) //02:12:42
String.Format("{0:hh:mm:ss tt}", System.DateTime.Now) //02:12:42 PM
此外,this网站在总结可以使用String.Format的各种方法方面非常有帮助。请记住,文化可以对非自定义格式产生影响。使用T
(长时间格式)的上述第一个示例可以在我的美国PC上运行。但如果你说:
String.Format(System.Globalization.CultureInfo.InvariantCulture, _
"{0:T}", System.DateTime.Now)
你以14:12:42结束。后两个例子是自定义格式,不受文化影响。
答案 1 :(得分:0)
使用适当的格式字符串进行显示。
string formatted = myDateTime.ToString("hh:mm:ss");
在这种情况下,我使用了custom format string。
答案 2 :(得分:0)
使用DateTime对象时,您实际上可以使用ToString()方法并在其中设置格式。
string currentTime = System.DateTime.Now.ToString("hh:mm:ss");
请查看此msdn文章以获得更清晰:
答案 3 :(得分:0)
1 - 使用正则表达式获取该字符串的前两个字符,即从23:11:59获得23
2 - 将此数字转换为整数类型
3 - 现在检查它是否不大于12,如果它是从它减去12并使用string.replace替换旧值。
答案 4 :(得分:0)
试试这个...
Dim CurTime As String
CurTime = TimeOfDay.ToString("h:mm:ss tt")