Nate Pet
Nate Pet

Reputation: 46222

c# show only Time portion of DateTime

I have a date that shows up as 10/18/2011 3:12:33 PM

How do I get only the time portion of this datetime?

I am using C#.

I tried:

      string timeval = PgTime.ToShortTimeString();

but that did not work as Intellisense only showed ToString();

Upvotes: 5

Views: 25924

Answers (5)

Misha Zaslavsky
Misha Zaslavsky

Reputation: 9646

In C# 10 you can use TimeOnly.

TimeOnly date = TimeOnly.FromDateTime(PgTime);

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74267

Don't now nothing about a class named PgTime. Do now about DateTime, though.

Try

DateTime instance = DateTime.Now           ; // current date/time
string   time     = instance.ToString("t") ; // short time formatted according to the rules for the current culture/locale

Might want to read up on Standard Date and Time Format Strings and Custom Date and Time Format Strings

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

Assuming that

DateTime PgTime;

You can:

String timeOnly = PgTime.ToString("t");

Other format options can be viewed on MSDN.

Also, if you'd like to combine it in a larger string, you can do either:

// Instruct String.Format to parse it as time format using `{0:t}`
String.Format("The time is: {0:t}", PgTime);

// pass it an already-formatted string
String.Format("The time is: {0}", PgTime.ToString("t"));

If PgTime is a TimeSpan, you have a few other options:

TimeSpan PgTime;

String formattedTime = PgTime.ToString("c"); // 00:00:00 [TimeSpan.ToString()]
String formattedTime = PgTime.ToString("g"); // 0:00:00
String formattedTime = PgTime.ToString("G"); // 0:00:00:00.0000000

Upvotes: 13

Brandon Poole
Brandon Poole

Reputation: 372

DateTime PgTime = new DateTime();
        var hr = PgTime.Hour;
        var min = PgTime.Minute;
        var sec = PgTime.Second;

        //or

        DateTime.Now.ToString("HH:mm:ss tt") gives it to you as a string.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

If you want a formatted string, just use .ToString(format), specifying only time portions. If you want the actual time, use .TimeOfDay, which will be a TimeSpan from midnight.

Upvotes: 2

Related Questions