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
533 views
in Technique[技术] by (71.8m points)

.net - Simple way to handle time in C#?

My current approach is something like

DateTime startHour = new DateTime(1900,1,1,12,25,43);
DateTime endHour = new DateTime(1900,1,1,13,45,32);

// I need to, say, know if a complete DateTime instance 
// is later than startHour plus 15 minutes

DateTime now = DateTime.Now();

startHour = startHour.addMinutes(15);

if (now.CompareTo(new DateTime(now.Year, now.Month, now.Day, startHour.Hour, 
                    startHour.Minute, startHour.Second)) > 0) 
{
    //I can do something now
}

This is very cumbersome and even failure prone. TimeSpans are not a solution as far as I can see, because they represent spans and aren't bound by the 24 hours limit (a TimeSpan of 56 hours 34 minutes is valid.)

What's the preferred approach for this type of calculations?

What am I missing?

EDIT: The calculations I'm after are ways to compare a complete DateTime instance with an hour, minute, second triplet representing an actual time of day and a way to operate over those triplets (add hours, minutes seconds).

EDIT 2: Thanks everybody, I got the gist of the DateTime API now, I think. :) The only thing I miss is a means to specify a TimeSpan that should represent a TimeOfDay only, but that's minor.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It's not at all clear what you mean by "is greater than startHour"... but taking

TimeSpan startHour = new TimeSpan(12, 25, 43);
if (endHour.TimeOfDay > startHour)
{
    ...
}

... works pretty simply.

By all means add argument checking to make sure that you don't specify a value for startHour which is < 0 or > 23 hours, but that's all pretty easy.

.NET's date and time API is quite primitive (even in 3.5) compared with, say, Joda Time - but in this particular case I think it's not too bad.


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

...