C# - 解析字符串,日期时间只用时:分:秒 [英] C# - Parsing a string to DateTime with just the hours:minutes:seconds

查看:261
本文介绍了C# - 解析字符串,日期时间只用时:分:秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到的小时,分​​钟和秒为整数用户输入。

I'm receiving the hours, minutes, and seconds as an integer user input.

现在,当我尝试使用DateTime.Parse和DateTime.TryParse AND Convert.ToDateTime,他们都返回正确的时/分/秒;然而,它也返回日期(年,月,日等)。

Now, when I try and use DateTime.Parse and DateTime.TryParse AND Convert.ToDateTime, they all return the correct hours/minutes/seconds; however, it also returns the date (year, month, day and so on.)

        string a = this.hours.ToString() + ":" + this.minutes.ToString() + ":" + this.seconds.ToString();

        this.alarm = new DateTime();
        this.alarm = DateTime.ParseExact(a, "H:m:s", null);

让我们说,时间是05年,分是21秒50。
中的将是5点21分五十零秒。我希望报警是5点21分50秒。然而,它实际上是(可能是):

Let's say that hours is 05, minutes is 21 and seconds is 50. "a" would be 05:21:50. I would expect "alarm" to be 05:21:50. However, it actually is (may be):

11/23/10 05:21:50

有没有什么办法让它工作的权利?先谢谢了。

Is there any way to make it work right? Thanks in advance.

推荐答案

一个DateTime的实例将始终包括一些最新信息。

A DateTime instance will always include some Date information.

如果你想代表一天刚刚的时候,你应该使用时间跨度(与代表自午夜起跨度时间跨度......或一天的时间,您还会注意到DateTime.TimeOfDay财产做同样的事情)。

If you're trying to represent just the time of day, you should use TimeSpan (with the TimeSpan representing the span since midnight...or the time of day. You'll also notice that the DateTime.TimeOfDay property does the same thing).

中的代码将类似于:

var timeOfDay = TimeSpan.ParseExact(a, "H:m:s", null);

这篇关于C# - 解析字符串,日期时间只用时:分:秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆