Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hour from C# DateTime without leading zero?

Tags:

c#

DateTime now = DateTime.Now;
        string time = now.ToString("h");

errors out saying I should parse the string first. The current time is 3 I don't want 03 I just want 3. "hh" returns 03 but I can't simply use "h".

like image 206
Christopher Bruce Avatar asked Feb 25 '14 22:02

Christopher Bruce


2 Answers

System.DateTime.Now.ToString("%h")

You have to specify that the format is custom.

like image 163
TyCobb Avatar answered Oct 02 '22 22:10

TyCobb


It sounds like you want standard int formatting. If so just call ToString on the Hour property

string time = now.Hour.ToString();

If you want 12 hour time then do the following

var hour = now.Hour > 12 ? now.Hour - 12 : now.Hour;
string time = hour.ToString();
like image 36
JaredPar Avatar answered Oct 02 '22 22:10

JaredPar