简体   繁体   English

最小日期和最大日期

[英]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. 我想从列表中找到MAXDATE和MIN DATE。请让我知道如何进行。

Regards, 问候,
Channa 昌娜

What format is that? 那是什么格式? "yyyyMMddtt" ? "yyyyMMddtt"

There is AM PM with date. 有上午PM与日期。 There is no time to accompany AM/PM. 没有时间陪同AM / PM。 So I am assuming AM is 00:00:00 and PM is 12:00:00 所以我假设上午是00:00:00,下午是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 如果日期格式为yyyyMMdd,则即使使用AM / PM,也可以按字符串排序

 nameList.Max()

If you have a year plus hours/minutes and AM/PM then you must parse to DateTime. 如果您有年份加上小时/分钟和AM / PM,则必须解析为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 由于您已在注释中将格式指定为yyyyMMdd ,因此需要从字符串中修剪PMAM

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 2012/6/18上午12:00:00
7/2/2012 12:00:00 AM 2012/7/2上午12:00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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