【问题标题】:How to assign a time value from a textbox to a variable?如何将文本框中的时间值分配给变量?
【发布时间】:2014-09-26 17:14:53
【问题描述】:

我试图弄清楚如何将文本框中的小时、分钟、秒和毫秒值设置为长变量,以便我可以在应用程序中操作时间值。

到目前为止,我尝试的是创建一个名为“workTime”的长变量,但我不确定如何将输入到文本框中的值分配为一段时间。

例如,如果用户输入“00 : 02 : 30 : 000”,我将如何将其分配给变量?

是否可以通过这种方式分配时间值?

任何建议或替代方法将不胜感激。

private void startBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {


            string wrkString;
            string rstString; 
            int i;

            //Assign text box time string to string variables.
            wrkString = wrkTbx.Text;
            rstString = restTbx.Text;


            //Assign text box string value to a date time variable.

            DateTime workDt = DateTime.ParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
            DateTime restDt = DateTime.ParseExact(rstString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);


            StopGoCvs.Background = new SolidColorBrush(Colors.Green);
            hornElmt.Play();
            //    // set up the timer
            myTimer = new DispatcherTimer();
            myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
            myTimer.Tick += myTimer_Tick;

            //tell timer to stop when it has reached the allocated work time.
            if(myTimer.Interval != workDt.TimeOfDay)
            {
                // start both timers
                myTimer.Start();
                myStopwatch.Start();

            }
            else
            {
                myTimer.Stop();
                myStopwatch.Stop();

            }



        }

【问题讨论】:

    标签: c# windows-phone-8 time stopwatch


    【解决方案1】:

    试试这个:

    DateTime dt = DateTime.ParseExact(time.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
    

    【讨论】:

    • 您缺少: 前后的空格。而且,持续时间(TimeSpan)比DateTime更适合这种情况。
    • @Xiaoy312 - 我更新了我的答案以考虑冒号之前或之后的任何空格。但是,我支持我对DateTime 的选择,因为TimeSpan 更多地是对经过时间或持续时间的衡量。根据他的描述,这听起来像是一天中的某个时间。
    • "workTime" 和 "as a period" 似乎另有说明。
    • @Xiaoy312 - “workTime”似乎向我暗示他指的是一天中的某个时间。例如,他在下午 3:00 开始工作。我们应该做的就是问问 OP。
    • @icemanind 是引用文本框内容的“时间”变量吗?
    【解决方案2】:
    //using System.Globalization
    
    TimeSpan.ParseExact("00 : 02 : 30 : 000", @"%h\ \:\ %m\ \:\ %s\ \:\ %fff", CultureInfo.InvariantCulture.DateTimeFormat)
    //from here you can decide to store the timespan value or the miliseconds via its 'TotalMilliseconds' property.
    
    
    //It may help with readability by removing the space from the input
    TimeSpan.ParseExact("00 : 02 : 30 : 000".Replace(" ", ""), @"%h\:%m\:%s\:%fff", System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      相关资源
      最近更新 更多