Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

visual studio - C# - Parsing a string to DateTime with just the hours:minutes:seconds

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...