为什么我的DateTime不正确?

时间:2013-08-30 00:31:44

标签: c# datetime

我正在尝试比较时间,我想用手机当前时间用于数学。现在我确定如果我能让这个字符串工作,那么我的应用程序将100%完成。

DateTime phonecurrentime =
    new DateTime(DateTime.Today.Day, DateTime.Now.Hour, DateTime.Now.Minute);

唯一的问题是...... -

testbox.Text = phonecurrentime.ToString("dd hh:mm");

显示不正确的时间:28 12:00 - ?????当那天真的是30日,时间是01:30

如何让它显示正确的一天?

3 个答案:

答案 0 :(得分:11)

为什么在手机当前时间为Now时使用构造函数创建实例。只需使用DateTime.Now

即可
DateTime phonecurrentime = DateTime.Now;

testbox.Text = phonecurrentime.ToString("dd hh:mm"); //30 01:30

您还应该使用AM / PM,因为hh将以00-12小时格式显示时间。您的日期时间格式应为"dd hh:mm tt"。在这种情况下,字符串将在下午30:30:30(如果是下半天)。

答案 1 :(得分:5)

您用来创建日期的电话是

DateTime(int year, int month, int day);

您的代码应该是读(如果您不关心年,月)

DateTime phonecurrentime =
    new DateTime(0, 0, DateTime.Today.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Seconds);

如果你关心年/月

DateTime phonecurrentime =
    new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Seconds);

或者只是

DateTime phonecurrentime = DateTime.Now;

答案 2 :(得分:2)

你使用了错误的构造函数。

DateTime(int year, int month, int day)

构造函数中的三个整数是上面的签名。你想要更长的版本:

DateTime(int year, int month, int day, int hour, int minute, int second)

像这样:

DateTime phonecurrentime =
new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);

或者简单地说:

DateTime phonecurrenttime = DateTime.Now;
相关问题