【问题标题】:Get the system date and split day, month and year获取系统日期和拆分日月年
【发布时间】:2012-10-20 07:01:13
【问题描述】:

我的系统日期格式是 dd-MM-yyyy(20-10-2012),我正在获取日期并使用分隔符来分割日期、月份和年份。无论格式是否以任何日期格式返回,我都需要转换日期格式(dd/MM/yyyy)。

string sDate = string.Empty;
DateTime _date = DateTime.Now;
int count = 0;
string format = "dd-MM-yyyy";
sDate = dateFormat.ToString(format);
string[] Words = sDate.Split(new char[] { '-' });
foreach (string Word in Words)
{
    count += 1;
    if (count == 1) { Day = Word; }
    if (count == 2) { Month = Word; }
    if (count == 3) { Year = Word; }
}

【问题讨论】:

  • 如果你已经有了DateTime 对象,为什么不能简单地使用它上面定义的属性呢? YearMonthDay 应该直接为您提供所需的值。我看不出转换为字符串的意义,然后你再乱用它来提取已经很容易获得的数据。

标签: c# asp.net


【解决方案1】:

如果没有打开 IDE 来检查我的大脑在一天中的这个时间是否能正常工作...

如果您只是想要特定格式的日期,您可以使用DateTime's .ToString(string format)。如果您点击该链接,则有许多标准和自定义格式字符串的示例。

所以

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

会以您要求的格式将日期作为字符串提供给您。

【讨论】:

    【解决方案2】:

    您可以按如下方式从当前日期拆分日期月份年份:

    DateTime todaysDate = DateTime.Now.Date;

    日期:

    int day = todaysDate.Day;

    月份:

    int month = todaysDate.Month;

    年份:

    int year = todaysDate.Year;

    【讨论】:

      【解决方案3】:

      这是您要查找的内容:

      String sDate = DateTime.Now.ToString();
      DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));
      
      String dy = datevalue.Day.ToString();
      String mn = datevalue.Month.ToString();
      String yy = datevalue.Year.ToString();
      

      或者,您可以在此处使用拆分功能到split string date into day, month and year

      希望,它会帮助你...干杯。 !!

      【讨论】:

      • 我不想粗鲁,但是你知道你的代码 sn-p 是做什么的吗?为什么要创建一个 DateTime 对象,然后调用 ToString() 两次并将其转换回 DateTime,以便第三次调用 ToString()?您只需要 DateTime dateValue = DateTime.Now;
      • @BojidarStanchev 亲爱的,我希望用户要求将日期字符串作为输入(尽管它是 DateTime 对象)。所以这仅适用于用例。我不想在运行时用不同类型的文化格式打扰用户。所以这只是一个基本规则。主要目的是展示如何轻松地将日、月、年从日期字符串中分离出来!
      【解决方案4】:

      你可以这样做:

       String date = DateTime.Now.Date.ToString();
          String Month = DateTime.Now.Month.ToString();
          String Year = DateTime.Now.Year.ToString();
      

      在日期时间的地方你可以使用你的专栏..

      【讨论】:

      • 您的示例中存在竞争条件,在某些日子非常接近午夜。
      【解决方案5】:

      如果你知道格式,你应该使用DateTime.TryParseExcact,或者如果你不知道并且想要使用系统设置DateTime.TryParse。并在参数中以正确的格式打印日期DateTime.ToString。要获取您拥有DateTime.YearDateTime.MonthDateTime.Day 的年、月或日。

      有关其他参考资料,请参阅 MSDN 中的 DateTime Structures

      【讨论】:

        【解决方案6】:

        TL&DR; C# 中的 DateTime 对象能够使用具有正确格式字符串的 ToString() 函数提取字符串信息。 (即:“yyyy-mm-dd”);

        string onlyDateWithoutTimeStamp = lastDate.ToString("yyyy-MM-dd");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-19
          • 2018-07-25
          相关资源
          最近更新 更多