开发者

Attendance management

开发者 https://www.devze.com 2023-02-10 21:22 出处:网络
I want to check the login time is am or pm and give the am checkbox to true otherwise pm is true.that is time is below 1pm the 开发者_高级运维the forenoon checkbox is true otherwise afternoon checkbox

I want to check the login time is am or pm and give the am checkbox to true otherwise pm is true.that is time is below 1pm the 开发者_高级运维the forenoon checkbox is true otherwise afternoon checkbox


As System.DateTime implements IFormattable, you can pass in format strings to the ToString method (or when using string.Format etc). One of those format strings is "tt", and it will give you either "AM" or "PM" based on the time.

DateTime time = GetAfternoonTime();
Console.Writeline(time.ToString("tt")); //Prints "PM"

time = GetMorningTime();
Console.Writeline(time.ToString("tt")); //Prints "AM"

Now if you want to bind that to a checkbox for example:

myAMCheckbox.Checked = dateTime.ToString("tt") == "AM";
myPMCheckbox.Checked = dateTime.ToString("tt") == "PM";

That code can obviously be optimised to only do the string conversion once. Also the advantage of this method is that you can easily make it globalised by passing in CultureInfo objects.

Example of making this culture aware:

CultureInfo culture = new CultureInfo("en-GB");

DateTime dateTime = GetSomeDateTime();

string AMorPM = dateTime.ToString("tt", culture);

myAMCheckbox.Checked = (AMorPM == culture.DateTimeFormat.AMDesignator);
myPMCheckbox.Checked = (AMorPM == culture.DateTimeFormat.PMDesignator);
0

精彩评论

暂无评论...
验证码 换一张
取 消