Reputation: 2871
I'm trying to create list of hours my code like
var hours = Enumerable.Range(00, 24).Select(i => i.ToString("D2")));
it generates something like this in 24 hour format but actually i need same thing not on 24 hours but 12 like after with AM PM postfix
what is the best way to generate hour list with 00.00 AM/PM
formatted
Thanks
Upvotes: 2
Views: 4526
Reputation: 4263
If you need more flexibility and have from/to for specific times that overlap midnight (and increase step to let's say every 2h) you can use something like this:
private static IEnumerable<string> GetListOfHours(DateTime start, DateTime end, int step)
{
while (start <= end)
{
yield return start.ToString("hh.mm tt");
start = start.AddHours(step);
}
}
So this:
var start = DateTime.Now.Date.AddHours(6); // 6 am
var end = DateTime.Now.AddDays(1).Date.AddHours(2); // 2 am
var step = 1;
var list = GetListOfHours(start, end, step);
Will produce this:
06.00 AM
07.00 AM
08.00 AM
09.00 AM
10.00 AM
11.00 AM
12.00 PM
01.00 PM
02.00 PM
03.00 PM
04.00 PM
05.00 PM
06.00 PM
07.00 PM
08.00 PM
09.00 PM
10.00 PM
11.00 PM
12.00 AM
01.00 AM
02.00 AM
https://dotnetfiddle.net/8LYxA6
Upvotes: 0
Reputation: 14640
You can create a DateTime
instance then use ToString
format of hh.mm tt
.
var hours = Enumerable.Range(00, 24)
.Select(i => new DateTime(2000,1,1,i,0,0).ToString("hh.mm tt"));
You need to execute the query using something like ToArray()
to get the result since the behavior of linq is deferred execution.
Upvotes: 8
Reputation: 54427
var hours = Enumerable.Range(00, 24).Select(i => (DateTime.MinValue.AddHours(i)).ToString("hh.mm tt"));
Upvotes: 5
Reputation: 125630
You're dealing with time, so using appropriate type, DateTime
, seems better than using int
:
var hours = from i in Enumerable.Range(0, 24)
let h = new DateTime(2014, 1, 1, i, 0, 0)
select h.ToString("t", CultureInfo.InvariantCulture);
Upvotes: 3
Reputation: 381
var startDate = DateTime.Today;
IEnumerable<DateTime> listOfHours = Enumerable.Range(0, 24).Select(h => startDate.AddHours(h));
Upvotes: 1