C# - Parsing a string to DateTime with just the ho

2019-06-20 01:55发布

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

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);

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.

5条回答
在下西门庆
2楼-- · 2019-06-20 02:21

As the other have mentioned here, a DateTimeobject will always contain a Datepart, but the easiest is just to ignore it. Then, when printing it out, you can use the following syntax:

alarm.ToShortTimeString();
查看更多
forever°为你锁心
3楼-- · 2019-06-20 02:22

A DateTime instance will always include some Date information.

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).

The code would be similar:

var timeOfDay = TimeSpan.ParseExact(a, "H:m:s", null);
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-06-20 02:29

You cannot do that, because DateTime, by design, represents a Date and a time.

There is no type in the .NET Framework designed to represent a time of day, but the closest would be TimeSpan. Consider wrapping it in your own TimeOfDay type, if Time-of-day semantics are important to you.

查看更多
手持菜刀,她持情操
6楼-- · 2019-06-20 02:38

The DateTime always holds time and date. If you want a class that only saves the time, you can create your own struct to handle that. But in the general case, there's no need to as you can simply ignore the date part of the DateTime struct, e.g.:

string a = "05:21:50";

DateTime alarm = new DateTime();
alarm = DateTime.ParseExact(a, "H:m:s", null);
Console.WriteLine(alarm.ToString("H:m:s"));
Console.WriteLine(alarm.Hour);
Console.WriteLine(alarm.Minute);
Console.WriteLine(alarm.Second);
查看更多
登录 后发表回答