如何在c#中使用DateAdd [英] How to use the DateAdd in c#

查看:93
本文介绍了如何在c#中使用DateAdd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello会员,



需要您的帮助如何在c#.net中使用DateAdd功能。我的问题是我有一个manufacturerDate和ExpireryDate文本框。我希望有效期可以计算从生产日期开始增加2年并在ExpiryDate文本框中自动触发到期日



谢谢

解决方案

如果我理解正确,您可以先解析生产日期文本框中的文本,然后使用AddYears计算到期日期。类似于:

 System.DateTime manufacturingDate; 
System.DateTime expirationDate;

if (System.DateTime.TryParse( 5.9.2010 out manufacturingDate)){
expirationDate = manufacturingDate.AddYears( 2 );
} 其他 {
// 不是有效日期
}



为了使其更可靠,您应该定义格式提供程序等,如 DateTime.TryParse方法(String,IFormatProvider,DateTimeStyles,DateTime%) [ ^ ]


您通过创建获得数据类型DateTime那个DateTime的obj然后如果该obj名称是TodayDate意味着TodayDate.Now使用此代码你可以获得今天的日期

你想在今天之后的2天添加意味着TodayDate.Now.AddDays(2 )过去2天意味着TodayDate.Now.AddDays(-1)

喜欢这个 -

DateTime TodayDate = new DateTime();

TodayDate = DateTime.Now;

TodayDate.AddDays(1);

TodayDate.AddDays(-1);

  public   class 示例
{
public static void Main()
{
TimeSpan interval = DateTime.Now - DateTime.Now.Date;
string msg = String .Format( 今天经过的时间:{0:d}小时。
interval);
Console.WriteLine(msg);
}
}


Hello members,

need your help how to use the DateAdd function in c#.net. My problem is i have a manufactureDate and the ExpireryDate text boxes. I would like the Expiry date should calculate when 2years are added from the manufacturing date and fires the expiry date automatically in the ExpiryDate textbox

Thank you

解决方案

If I understood correctly, you can first parse the text in the manufacturing date text box and then using AddYears calculate the expiration date. Something like:

System.DateTime manufacturingDate;
System.DateTime expirationDate;

if (System.DateTime.TryParse("5.9.2010", out manufacturingDate)) {
   expirationDate = manufacturingDate.AddYears(2);
} else {
   // not a valid date
}


To make it more reliable you should define the format provider etc. as in DateTime.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTime%)[^]


You have the Datatype DateTime by Creating the obj for that DateTime then if that obj name is TodayDate means TodayDate.Now using this code you can get the today date
The you want to add 2 days after today means TodayDate.Now.AddDays(2) pervious 2 days means TodayDate.Now.AddDays(-1)
like this--
DateTime TodayDate = new DateTime();
TodayDate = DateTime.Now;
TodayDate.AddDays(1);
TodayDate.AddDays(-1);


public class Example
{
   public static void Main()
   {
      TimeSpan interval = DateTime.Now - DateTime.Now.Date;
      string msg = String.Format("Elapsed Time Today: {0:d} hours.",
                                 interval);
      Console.WriteLine(msg);
   }
}


这篇关于如何在c#中使用DateAdd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆