简体   繁体   中英

how to get AM/PM from datetime? c#

I have a date like this:

equipBooking.BookedFromDteTme.Date = `{12/5/2013 12:00:00 AM}`

and I want to apply time like this, but I do not know how to get AM and PM from the end.

dtStartTimeHour.SelectedItem = equipBooking.BookedFromDteTme.TimeOfDay.Hours;
dtStartTimeMin.SelectedItem = equipBooking.BookedFromDteTme.TimeOfDay.Minutes;
**dtStartTimeAMPM.SelectedItem = equipBooking.BookedFromDteTme.???????.;**

Please help me.

I have tried something like this:

var startDatestr = equipBooking.BookedFromDteTme.TimeFrom.Split(new string[] { ":", ":",":",":" }, StringSplitOptions.RemoveEmptyEntries);

AM/PM = startDatestr[3]

If you just want the string you can do:

equipBooking.BookedFromDteTme.ToString("tt");

Or for a boolean result use:

bool isPM = (equipBooking.BookedFromDteTme.Hour >= 12);

BTW, you don't need to call TimeOfDay - you can get the Hour and Minute property directly from the DateTime :

dtStartTimeHour.SelectedItem = equipBooking.BookedFromDteTme.Hour;
dtStartTimeMin.SelectedItem = equipBooking.BookedFromDteTme.Minute;
dtStartTimeAMPM.SelectedItem = equipBooking.BookedFromDteTme.ToString("tt");

TimeSpan does not store time-of-day, but rather the length of any interval of time. It has no notion of AM/PM.

TimeOfDay returns the amount of time since midnight.

If Hours is more than or equal to 12, that will be PM.

尝试使用dateTime.ToString("tt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM