开发者

Calculate time difference in c# windows phone 7

I am trying to calculate the time difference between 2 time and put the result into a text block.

For example,

Start time: 9:45 AM

End start: 5:15 PM

How can i calulate the time difference between it?

DateTime dt1 = DateTime.ParseExa开发者_开发问答ct(DateTime.Now.ToShortTimeString(), "hh:mm tt", new DateTimeFormatInfo());

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

TimeSpan ts1 = dt2.Subtract(dt1);


For time "11:12 PM" you should use format "h:mm tt". So, you parse two time strings and make Subtract or just (dateTime1 - dateTime2).


try:

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);


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.");

}

or try

    /* 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);


The method suggested by O.D. is what I use in my app that uses a time difference. I then use the method ng_ducnghia suggests to separate units of time (hours, min, sec - I don't need millisec for my purpose).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜