在推导出将下拉列表绑定(bind)到一组时间间隔的逻辑后,我希望在术语方面得到改进
使用为日期和时间设计的原生数据类型
让它可配置
伪代码
for (var hoursCount = 0; hoursCount <= 12; i++) {
for (var timeSlots = 0; timeSlots < 2; j++) {
string hourAndMinute = hoursCount;
if (timeSlots == 0) {
hourAndMinute += ":00 AM";
} else {
hourAndMinute += ":30 AM";
}
if (hourAndMinute != "12:00 AM" || hourAndMinute != "12:30 AM") {
alert(hourAndMinute);
}
}
}
输出
0:00 AM
0:30 AM
.
.
.
12:30 AM
最佳答案
不清楚您在这里想要哪种“配置”,但由于您只处理时间,我个人会使用 Noda Time它具有用于处理此类事情的 LocalTime
结构。 (免责声明:我是 Noda Time 的主要开发人员,所以我有点偏见。)您可以只使用 DateTime
,但因为您不需要约会...
不太清楚你想要什么样的“配置”,但在 Noda Time 中你可以这样写:
LocalTimePattern pattern = LocalTimePattern.CreateWithInvariantInfo("hh:mm tt");
for (var hour = 0; hour <= 12; hour++) {
for (var slot = 0; slot < 2; slot++) {
LocalTime time = new LocalTime(hour, slot * 30, 0);
Console.WriteLine(pattern.Format(time));
}
}
有了关于您想做什么的更多详细信息,我们无疑可以提供更多帮助。
编辑:好的,听起来您可能想要这样的东西:
static void DisplaySlots(string format, Period slotLength, int slots)
{
// Or change the parameter to be a LocalTimePattern
LocalTimePattern pattern = LocalTimePattern.CreateWithInvariantInfo(format);
LocalTime time = LocalTime.Midnight;
for (int i = 0; i < slots; i++)
{
Console.WriteLine(pattern.Format(time));
time = time + slotLength;
}
}
然后调用它:
DisplaySlots("HH:mm", Period.FromMinutes(20), 100);
(或其他...)
使用 DateTime
的替代方法:
static void DisplaySlots(string format, TimeSpan slotLength, int slots)
{
DateTime time = DateTime.Today;
for (int i = 0; i < slots; i++)
{
Console.WriteLine(time.ToString(format));
time = time + slotLength;
}
}
关于C# 在下拉列表中显示时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9835050/