转换后的字符串格式不正确

时间:2014-11-25 21:48:54

标签: visual-studio-2010 visual-studio-2012 c++-cli

首先,我知道有很多像我这样的问题,但在分析之后,我会知道该怎么做,但最终还是会出错。 我正在使用visual studio 2012和c ++语言创建时间卡窗体,如下所示。 http://i1294.photobucket.com/albums/b618/uRsh3RRaYm0nD/checkin_zpsa4ccebda.jpg

如您所见,我能够将datetimepicker范围值转换并计算为字符串,以便在“小时”文本框下方显示这些值。 我遇到问题的地方是编码Total Hours Get按钮,它会减去两个小时的文本框,以便在Total Hours文本框中显示它们。 我已经尝试将这些字符串值转换回DateTime,执行计算,然后将结果转换为字符串以显示它。

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
         if( this->dtpMondayIn->Value > this->dtpMondayOut->Value )
     this->dtpMondayIn->Value = this->dtpMondayOut->Value;
         System::TimeSpan diff = this->dtpMondayOut->Value.Subtract(this->dtpMondayIn->Value);
         txtMonday->Text = Convert::ToString(diff);
     }
private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
         if(this->dtpLunchIn->Value > this->dtpLunchOut->Value)
             this->dtpLunchIn->Value = this->dtpLunchOut->Value;
         System::TimeSpan diff2 = this->dtpLunchOut->Value.Subtract(this->dtpLunchIn->Value);
         txtLunch->Text = Convert::ToString(diff2);
     }
private: System::Void get1_Click(System::Object^  sender, System::EventArgs^  e) {
            DateTime lunch, work, total;
            lunch = Convert::ToDateTime(txtLunch->Text);
            work = Convert::ToDateTime(txtLunch->Text);
            total = lunch - work;
            txtTotalHours->Text = Convert::ToString(total);
//This is where I get the error  error C2440: '=' : cannot convert from 'System::TimeSpan' to 'System::DateTime

1 个答案:

答案 0 :(得分:0)

使用TimeSpan计算持续时间。 DateTime按照它在锡上所说的那样,它代表了一个时刻。

private: System::Void get1_Click(System::Object^  sender, System::EventArgs^  e) 
{
    TimeSpan work, lunch, total;

    work = this->dtpMondayOut->Value.Subtract(this->dtpMondayIn->Value);
    lunch = this->dtpLunchOut->Value.Subtract(this->dtpLunchIn->Value);
    total = lunch - work;

    txtTotalHours->Text = Convert.ToDecimal(total->TotalHours).ToString("#.00");
}

编辑:更改了txtTotalHours输出以匹配提供的图像的十进制输出。