如何在C#中找到当前的年,年,月和日?

时间:2017-10-11 10:26:36

标签: c#

我有一个申请表要求我获得以下内容:

    int doy // Day of the year
    int yr  // Two digit year
    int mon // Two digit month (zero on left for small numbers)
    int day // Two digit day   (zero on left for small numbers)

有谁能告诉我如何使用C#获取这些数字?

3 个答案:

答案 0 :(得分:4)

System.DateTime moment = new System.DateTime.Now;

int year = moment.Year;
int month = moment.Month;
int day = moment.Day;
int hour = moment.Hour;
int minute = moment.Minute;
int second = moment.Second;
int millisecond = moment.Millisecond;

看看这里:MSDN Documentation - DateTime

答案 1 :(得分:3)

像这样

Console.WriteLine(DateTime.Now.DayOfYear); // day of year
Console.WriteLine(DateTime.Now.Month); // month of year 
Console.WriteLine(DateTime.Now.Year); // year 

根据文化计算一周中的一周,如果星期一开始,因为其他文化不会像阿拉伯语那样在星期一开始

int day = DateTime.Now.DayOfYear;
var week = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

获取周数的简便方法是

  Console.WriteLine( System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday));

答案 2 :(得分:-2)

要获得左边填0的数字,你必须使用字符串格式。

        int doy = DateTime.Now.DayOfYear;// Day of the year
        string yr = DateTime.Now.ToString("yy");// Two digit year
        string mon = DateTime.Now.Month.ToString("d2"); // Two digit month (zero on left for small numbers)
        string day = DateTime.Now.Day.ToString("d2"); // Two digit day   (zero on left for small numbers)
    Console.WriteLine(doy);
    Console.WriteLine(yr);
    Console.WriteLine(mon);
    Console.WriteLine(day);