显示过去和未来的日期 asp.net c#

show past and future date asp.net c#

我需要显示如下日期。 (日期为西班牙语)

Lunes 16 de marzo | Martes 17 de marzo | Miércoles 18 de marzo | Jueves 19 de marzo | Viernes 20 de marzo 20

我需要显示5个日期,组中的第三个日期必须是今天。

有人知道如何开始吗?

你可以使用这样的东西:

DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
DateTime yesterday = today.AddDays(-1);

然后您只需按需要格式化输出即可。

在C#中,可以使用DateTime对象获取当前DateTime,然后使用DateTime的方法获取前2个和后2个。DateTime的AddDay(或AddMinute、Second等...)可以取负数数.

DateTime myDate = DateTime.Now;
DateTime prevOne = myDate.AddDays(-1);
DateTime prevTwo = myDate.AddDays(-2);
DateTime nextOne = myDate.AddDays(1);
DateTime nextTwo = myDate.AddDays(2);

按照prevTwo、prevOne、myDate、nextOne、nextTwo的顺序显示。我假设您的区域设置负责翻译成西班牙语。

伪代码:

Declare a string
For (var i=0; i<5;i++)
{      
  string += " (today -2 +i) formatted in any way you want "
}
Display the string

我会按照这些思路做某事:

Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
//Format your date 'de' to get the literal string into the date
var datestring = "{0:dddd dd 'de' MMMM}";

StringBuilder sb = new StringBuilder();
//iterate
for(int x = 0; x < 5; x++)
{
   //build the string
    sb.Append(String.Format(datestring + " | ", DateTime.Now.AddDays(-2+x)));
}
sb.ToString().Dump();

输出:

martes 17 de marzo | miércoles 18 de marzo | jueves 19 de marzo | viernes 20 de marzo | sábado 21 de marzo

编辑:更好的方法,去掉尾随的“|”并将数据聚合与演示分开:

Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");

var dateFormat = "dddd dd 'de' MMMM";
List<DateTime> dates = new List<DateTime>();
for(int x = 0; x < 5; x++)
{
    //push dates into our List
    dates.Add(DateTime.Now.AddDays(-2+x));
}
//build the output string and format our dates
String.Join(" | ", dates.Select (d => d.ToString(dateFormat))).Dump();

在这里,内联评论:

using System;
using System.Linq;
using System.Text;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        // slecting locale
        var ci = new CultureInfo("es-ES");

        // use a StringBuilder for storing the processed text
        var sBuilder = new StringBuilder();

        // use an Enumerable
        Enumerable.Range(-2, 5)
            // get date range
            .Select(i => DateTime.Today.AddDays(i))
            // get long dates in es-ES and remove ","
            .Select(i => i.ToString("D", ci).Replace(",", ""))
            .ToList().ForEach(s =>
            {
                // capitalize first letter
                sBuilder.Append(char.ToUpper(s[0]));
                // remove the year part
                sBuilder.Append(s.Substring(1, s.LastIndexOf(' ') - 3));
                // add delimiter
                sBuilder.Append("| ");
            });
        // adjust length for removing the final delimiter
        sBuilder.Length = sBuilder.Length - 2;

        Console.WriteLine(sBuilder.ToString());
    }
}