在C#中修改DateTime的信息 [英] Modifying information of DateTime in C#

查看:966
本文介绍了在C#中修改DateTime的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,又是我.我很高兴,因为大家都帮助我简化了工作.

我有一个简单但又大的问题:

Hey it''s me again. I''m happy because all of you help me to make my job easier.

I have a simple but big problem:

//a date with an hour
DateTime date = DateTime.Parse("2011-02-01 00:23:50");
//I tried doing this too:
DateTime date = new DateTime(2011,2,1,0,23,50);

//It doesn''t work and I don''t know why:
date.AddHour(-1);
// It doesn''t work eighter
date.AddDay(1);



我想从这个日期时间减去一个小时,我应该有这样的东西:2011-01-31 23:23:50
事实是,我想添加或减去我想要的任何内容(一年,一天,一月,一小时,一分钟或一秒钟),而不仅仅是一个小时.有自动功能吗?

谢谢!



I want to substract an hour from this datetime I should have something like this: 2011-01-31 23:23:50
The fact is that I want to add or substract anything I want (a year, day, month, hour, minute or second) and not just an hour. Is there any automatic function?

Thanks!

推荐答案

别忘了,时间和持续时间是不同的事情.您还需要持续时间.时间用DataTime表示,但是持续时间(对于时间算术更强大)用TimeSpan表示.我的提示已经被接受了吗?

如果没有,请继续阅读:

Don''t forget, time and duration are different things. You also need duration. Time is represented by DataTime, but duration — more powerful for time arithmetics — by TimeSpan. Is my hint already taken?

If not, please keep reading:

DateTime time = DateTime.Now;
int days = 13;
int hours = 12;
int minutes = 55;
int seconds = 12;
time -= new TimeSpan(days, hours, minutes, seconds);

//lookup all the overloaded constructors for more detail...

time += new TimeSpan(days, hours);



现在,您的想法应该已经完全清楚了.使用TimeSpan,您可以执行您可能期望的任何合理的时间算术运算.

旁注:此类算术运算的一个有用应用是测量时间:您可以从另一时间中减去一次,返回结果为TimeSpan:



Now the idea should be completely clear for you. With TimeSpan, you can do any reasonable time arithmetic operation you might expect.

Side note: one useful application of such arithmetic operations is measuring time: you can subtract one time from another, returned result is TimeSpan:

DateTime before = DateTime.Now;
//some timely operation here
DateTime after = DateTime.Now;

TimeSpan delay = after - before;
double ms = delay.TotalMilliseconds;
double hours = delay.TotalHours;

//...




—SA




—SA


OH可能是上帝!

我没有意识到这是如此简单:

date.AddHour(-1)是一个返回带有新信息的DateTime的函数,因此,如果我不将新值分配给任何变量,我将永远遇到相同的问题:

解决方法如下:

OH MIGHTLY GOD!

I didn''t realize it was such an easy solucion:

date.AddHour(-1) is a function that returns a DateTime with the new information, so if I don''t assign the new value to any variable I will have the same problem forever:

here is the solution:

date = date.AddHour(-1);


这篇关于在C#中修改DateTime的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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