Solution 1 : You can use ToString()
function with custom date format strings
to get the required part of the DateTime
string.
1. You need to use small hh
for getting the hours in 12
Hour format.
2. You need to use tt
for getting the AM
or PM
string.
Try
string Hours = DateTime.Now.ToString("hh");
string AMorPM = DateTime.Now.ToString("tt");
For complete Time Info:
DateTime dt = DateTime.Now;
int hours = Convert.ToInt32(dt.ToString("hh"));
int minutes = dt.Minute;
int seconds = dt.Second;
string AMorPM = dt.ToString("tt");
Solution 2: You can perfomr the mod operation with 24 hour value with 12 to get the 12 hour value.
Note: You need to map result (after mod operation) to 1 if it is 0
.
int hours = (dt.Hour % 12 != 0) ? dt.Hour : 1;
string AMorPM = dt.ToString("tt");