2017-08-17 108 views
-2

我想创建一个DateTime对象,但它似乎给我一个错误。Converting Year,Month to DateTime

int month = "1" 
int year = "2017" 

DateTime date = new DateTime(year, month, DateTime.Day); 

它似乎不喜欢DateTime.Day。它表示非静态字段需要对象引用。

我怎么能得到今天(第16)作为参数?另外,我需要日期有hh:mm:sss ...我怎么能这样做?

感谢您的帮助!

+0

这是唯一的年份和月份? –

+0

我只有年份和月份的值,但我希望今天是今天。有没有办法让它通过DateTime?我试图把这个日期插入到数据库中,所以我试图得到今天的日子和时间。 – vanillacoke9191

+0

在上面的另一个变量中取datetime.now.day并传递它。 – Amit

回答

-1

它应该是:

int month = 1; 
int year = 2017; 

DateTime date = new DateTime(year, month, DateTime.Now.Day); 

拿笔记,你声明整数无quotation马克:

int month = 1; 

将其与毫秒转换24小时制的意见的要求:

string strResult = string.Format("{0:MM/dd/yyyy HH:mm:ss.fff}", date); 
//Results: 02/17/2017 00:00:00.000 

12小时:

string strResult = string.Format("{0:MM/dd/yyyy hh:mm:ss.fff}", date); 
//Results: 02/17/2017 12:00:00.000 
+0

打印出来的格式是01/16/2017 12:00:00 AM。打印日期时间,我怎样才能制作2017/01/16 12:00:00:000的格式? – vanillacoke9191

+0

'month == 2'和'DateTime.Now.Day == 30'会发生什么? – Enigmativity

+0

@ vanillacoke9191我根据您的要求更新了我的代码。 –

1

使用

var day = DateTime.Now.Day; 

今天。在构造SSS到日期对象太:

可以添加HH:MM

DateTime date = new DateTime(year, month, DateTime.Now.Day, 10, 11, 12); 
  • 10 =>小时
  • 11 =>分钟
  • 12 = >秒

当然你可以使用DateTime.N ow.Hour等等的当前值。如果值是无效的一个真正的日期,例如


一种ArgumentOutOfRangeException被抛出30.2.xxxx。


可以打印日期对象以不同的格式,阅读MS Documentation对所有的可能性。

+0

10,11,12是什么意思?谢谢! – vanillacoke9191

+0

10 =>小时; 11 =>分钟; 12 =>秒当然你可以使用DateTime.Now.Hour等等当前值 – Eisfuchs

+0

当'month == 2'和'DateTime.Now.Day == 30'发生什么? – Enigmativity

相关问题