Reputation: 83
I have a list of dates as below
List<string> nameList = new List<string>();
nameList.Add("20120618PM");
nameList.Add("20120622PM");
nameList.Add("20120622AM");
nameList.Add("20120628PM");
nameList.Add("20120702PM");
nameList.Add("20120629AM");
nameList.Add("20120629PM");
I want to find MAXDATE and MIN DATE from the list .Please let me know how can i proceed.
Regards,
Channa
Upvotes: 0
Views: 3543
Reputation: 5367
// 1. Convert your string list to datetimes
IEnumerable<DateTime> dates = nameList.Select(m => DateTime.Parse(m, yourFormatProvider));
// 2. Get first and last date
DateTime maxDate = dates.Max();
DateTime minDate = dates.Min();
Upvotes: 2
Reputation: 223257
Since you have specified your format as yyyyMMdd
in your comment, you need to trim PM
and AM
from the string
List<DateTime> dateList =
nameList.Select(x =>
DateTime.ParseExact(
x.TrimEnd("PM".ToCharArray()).TrimEnd("AM".ToCharArray()),
"yyyyMMdd",
CultureInfo.InvariantCulture)
).ToList();
var Minimum = dateList.Min();
var Maximum = dateList.Max();
Console.WriteLine(Minimum.ToString());
Console.WriteLine(Maximum.ToString());
This will give you:
6/18/2012 12:00:00 AM
7/2/2012 12:00:00 AM
Upvotes: 1
Reputation: 48568
What format is that? "yyyyMMddtt"
?
There is AM PM with date. There is no time to accompany AM/PM. So I am assuming AM is 00:00:00 and PM is 12:00:00
First correct your format then use this
List<DateTime> temp = nameList.Select(x =>
DateTime.ParseExact(x, "yyyyMMddtt", CultureInfo.InvariantCulture)).ToList();
Then
temp.Min("yyyyMMddtt");
temp.Max("yyyyMMddtt");
Upvotes: 6
Reputation: 11101
If the date format is yyyyMMdd then is is sortable as strings even with AM/PM
nameList.Max()
If you have a year plus hours/minutes and AM/PM then you must parse to DateTime. I recommend parsing regardless, as suggested in other answers.
Upvotes: 4
Reputation: 35716
If I had to guess, which it seems I do. I would do this
var dates = nameList.ConvertAll(s => {
var dateString = s.SubString(6);
var timeString = s.SubString(7, 2);
var date = DateTime.Parse(dateString);
if (timeString == "PM")
{
date = date.AddHours(12);
}
return date;
});
var max = date.Max();
var min = date.Min();
Upvotes: 1