繁体   English   中英

C#如何将两个或多个整数转换为日期?

[英]C# How do I convert two or more integers into a date?

如何将实例28和03的两个整数转换为类似“ 28.03”的日期。 应该从用户输入整数,然后将其转换为日期。 另外,如何在日期中增加天数?

只是您的示例的一个实现:

public static string GetDateString(int month, int day)
{
    return new DateTime(DateTime.Now.Year, month, day).ToString("dd.MM");
}

要将日期添加到日期,可以使用DateTime.AddDays()方法:

DateTime date = DateTime.Now;
DateTime otherDate = date.AddDays(7);

@Giorgi和@D提到的链接。 彼得罗夫(Petrov)也非常有用。

更新:

这是一个基于您的评论的示例。

class ConsoleApp
{
    public void Main(string[] args)
    {
        int day = int.Parse(Console.ReadLine());
        int month = int.Parse(Console.ReadLine());

        string formattedDate = GetDateString(month, day);

        Console.WriteLine(formattedDate);

        // You cannot initialize a DateTime struct only with month and day.
        // Because Year is not relevant we use the current year.
        DateTime date = new DateTime(DateTime.Now.Year, month, day);
        DateTime otherDate = date.AddDays(5);

        Console.WriteLine(GetFormattedDate(otherDate));
    }

    public static string GetFormattedDate(DateTime date)
    {
        // The ToString() method accepts any custom date format string.
        // Here is how you can create a custom date format string:
        // https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx

        // dd: days in two digits
        // MM: months in two digits
        return date.ToString("dd.MM");
    }

    public static string GetDateString(int month, int day)
    {
        // Here we construct a DateTime struct
        DateTime date = new DateTime(DateTime.Now.Year, month, day);

        // Now we extract only the day and month parts.
        return GetFormattedDate(date);
    }
}

好吧,如果28是一天和03个月-您可以将这些参数传递给DateTime结构对象的构造函数。 初始化DateTime对象后,可以通过多种方法将其转换为字符串。 它还具有AddDays方法。

关于您需要的内容有很多文档(特别是DateTime结构)。 有关您当前需求的最相关信息以及使用日期格式化字符串的不同方法,您可以在这里找到: https : //msdn.microsoft.com/zh-cn/library/8kb3ddd4(v= vs.110).aspx但是正如我之前提到的,网络上有很多信息。

暂无
暂无

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

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