【问题标题】:Calculate time difference in c# windows phone 7在 c# windows phone 7 中计算时间差
【发布时间】:2011-08-04 06:09:22
【问题描述】:

我正在尝试计算两次之间的时间差并将结果放入文本块中。

例如,

开始时间:上午 9:45

结束开始时间:下午 5:15

我如何计算它们之间的时间差

DateTime dt1 = DateTime.ParseExact(DateTime.Now.ToShortTimeString(), "hh:mm tt", new DateTimeFormatInfo());

        DateTime dt2 = DateTime.ParseExact(timePicker1.ValueString, "hh:mm tt", new DateTimeFormatInfo());

时间跨度 ts1 = dt2.Subtract(dt1);

【问题讨论】:

标签: c#


【解决方案1】:

对于时间“11:12 PM”,您应该使用格式“h:mm tt”。因此,您解析两个时间字符串并生成 Subtract 或只是 (dateTime1 - dateTime2)。

【讨论】:

  • 我用代码修改了我的问题。还是有同样的问题
  • 你应该使用“hh:mm tt”而不是“hh:mm:tt”。
  • 已更改。还是同样的错误。不知道有什么问题
  • dt2 时间来自时间选择器
  • timePicker1.ValueString 的值可能有问题。它是否有正确的时间格式或诸如“13:25 AM”之类的东西?我试图运行我的代码并且它有效。尝试在没有 timePicker1.ValueString 的情况下使用您的代码。
【解决方案2】:

尝试:

DateTime dt1 = DateTime.ParseExact("22:22:22", "HH:mm:ss", new DateTimeFormatInfo());
DateTime dt2 = DateTime.ParseExact("11:11:11", "HH:mm:ss", new DateTimeFormatInfo());
TimeSpan ts1 = dt1.Subtract(dt2);

【讨论】:

    【解决方案3】:
    protected void Page_Load(object sender, EventArgs e)
    {
        // Declare and get DateTime values
        DateTime StartDate = System.DateTime.Now;
        DateTime EndDate = System.DateTime.UtcNow;
    
        // Find time difference between two dates
        TimeSpan TimeDifference = StartDate - EndDate;
    
        // Write difference in hours and minutes
        Response.Write("Time difference between server time and Coordinated Universal Time (UTC) is " +
            TimeDifference.Hours.ToString() + " hours ");
        if (TimeDifference.Minutes != 0)
            Response.Write(" and " + TimeDifference.Minutes.ToString() + " minutes.");
    
    }
    

    或者试试

        /* Read the initial time. */
    DateTime startTime = DateTime.Now;
    Console.WriteLine(startTime);
    
    /* Do something that takes up some time. For example sleep for 1.7 seconds. */
    Thread.Sleep(1700);
    
    /* Read the end time. */
    DateTime stopTime = DateTime.Now;
    Console.WriteLine(stopTime);
    
    /* Compute the duration between the initial and the end time. 
     * Print out the number of elapsed hours, minutes, seconds and milliseconds. */
    TimeSpan duration = stopTime - startTime;
    Console.WriteLine("hours:" + duration.Hours);
    Console.WriteLine("minutes:" + duration.Minutes);
    Console.WriteLine("seconds:" + duration.Seconds);
    Console.WriteLine("milliseconds:" + duration.Milliseconds);
    

    【讨论】:

      【解决方案4】:

      O.D. 建议的方法是我在使用时差的应用程序中使用的。然后我使用 ng_ducnghia 建议的方法来分隔时间单位(小时、分钟、秒 - 我不需要毫秒)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        相关资源
        最近更新 更多