简体   繁体   中英

Min Date and Max date

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

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");

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.

// 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();

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM