我想知道如何循环播放日期时间或任何类型的变量,每隔30分钟从上午12:00到下午11:59?
所以我需要一个变量来显示12HR格式的时间(01:00 PM,09:00 AM),每次我循环播放它,到时间增加30分钟?然后我需要在字符串中使用此值。
时间需要从上午10:00开始
答案 0 :(得分:15)
总有LINQ
var start = DateTime.Today;
var clockQuery = from offset in Enumerable.Range(0, 48)
select start.AddMinutes(30 * offset);
foreach (var time in clockQuery)
Console.WriteLine(time.ToString("hh:mm tt"));
... LINQ + FUNC(用于参数化启动)
Func<DateTime, IEnumerable<DateTime>> clockQuery = start =>
from offset in Enumerable.Range(0, 48)
select start.AddMinutes(30 * offset);
foreach (var time in clockQuery(DateTime.Today))
Console.WriteLine(time.ToString("hh:mm tt"));
...或者如果您只想要TimeSpan偏移......
var start = DateTime.Today;
var clockQuery = from offset in Enumerable.Range(0, 48)
select TimeSpan.FromMinutes(30 * offset);
foreach (var time in clockQuery)
Console.WriteLine((start + time).ToString("hh:mm tt"));
答案 1 :(得分:6)
您可以使用扩展方法:
public static class DateTimeHelper
{
public static IEnumerable<DateTime> GetHalfHours(this DateTime dt)
{
TimeSpan ts = TimeSpan.FromMinutes(30);
DateTime time = dt;
while(true)
{
yield return time;
time.Add(ts);
}
}
}
答案 2 :(得分:2)
DateTime可以做简单的算术:
DateTime time = DateTime.Now;
time = time + TimeSpan.FromMinutes(1);
使时间增加一分钟。
您可以使用Timer类,并根据每tick个适当的时间增加DateTime。如果确切性在这里很重要,那么还有其他更合适的计时器类。
TimeSpan类还有其他静态方法!
答案 3 :(得分:1)
这样的事情?
DateTime timeloop = new DateTime(0);
timeloop = timeloop.Add(new TimeSpan(10, 00, 0)); //start at 10:00 AM
for (int i = 0; i < 48; i++)
{
string time =timeloop.ToString("hh:mm tt"); //print it as 1:30 PM
timeloop = timeloop.Add(new TimeSpan(0, 30, 0)); //add 30 minutes
}
答案 4 :(得分:1)
var times = new List<string>();
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for (var i = today; i < tomorrow; i = i.AddMinutes(30))
{
times.Add(i.ToShortTimeString());
}
答案 5 :(得分:0)
DateTime time = new DateTime(2011,02,22,10,0,0);
List<String> times = new List<string>();
for (int i = 0; i < 48; i++)
{
time = time.AddMinutes(30);
times.Add(time.ToString());
}
这可能会做你需要的事情
答案 6 :(得分:0)
这样的事情对你有用:
int workCount = 0;
var timer = new System.Timers.Timer(1800000); // every half hour
timer.AutoReset = true;
timer.Elapsed += (src, e) =>
{
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
if(++workCount == 48)
{
timer.Stop();
}
};
timer.Start();
答案 7 :(得分:0)
DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddDays(-1);
while (startDate.AddMinutes(30) <= endDate)
{
string sdate = startDate.ToString("yyyy-MM-dd HH:mm");
string edate = startDate.AddMinutes(29).ToString("yyyy-MM-dd HH:mm");
string display = string.Format("{0} - {1}", sdate, edate);
Console.WriteLine(display);
startDate = startDate.AddMinutes(30);
}