Csharp/C Sharp/Development Class/TimeSpan

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Calculation based on the TimeSpan

using System;
class Test
{
    public static void Main()
    {
        // Create a TimeSpan representing 6.5 days.
        TimeSpan timespan1 = new TimeSpan(6, 12, 0, 0);
        // Create a TimeSpan representing 0.5 days.
        TimeSpan timespan2 = new TimeSpan(0, 12, 0, 0);
        TimeSpan oneWeek = timespan1 + timespan2;
        DateTime now = DateTime.Now;
        DateTime past = now - oneWeek;
        // Create a DateTime representing 1 week in the future.
        DateTime future = now + oneWeek;
        // Display the DateTime instances.
        Console.WriteLine("Now   : {0}", now);
        Console.WriteLine("Past  : {0}", past);
        Console.WriteLine("Future: {0}", future);
    }
}


Measuring the Time Taken to Add Some Numbers

 
using System;
class MainClass {
    public static void Main() {
        DateTime start = DateTime.Now;
        long total = 0;
        for (int count = 0; count < 1000000; count++) {
            total += count;
        }
        TimeSpan timeTaken = DateTime.Now - start;
        Console.WriteLine("Milliseconds = " + timeTaken.Milliseconds);
        Console.WriteLine("total = " + total);
    }
}


new TimeSpan( 0)

 
using System;
    class MainClass
    {
        public static void Main()
        {
            TimeSpan timespan1 = new TimeSpan(2, 12, 0, 0);
            TimeSpan timespan2 = new TimeSpan(4, 12, 0, 0);
            TimeSpan oneWeek = timespan1 + timespan2;
            DateTime now = DateTime.Now;
            DateTime past = now - oneWeek;
            DateTime future = now + oneWeek;
            Console.WriteLine("Now   : {0}", now);
            Console.WriteLine("Past  : {0}", past);
            Console.WriteLine("Future: {0}", future); 
       }
    }


Subtract 15 minutes from the current TimeSpan and print the result

 
using System;
using System.Collections.Generic;
using System.Text;
class Program {
    static void Main(string[] args) {
        TimeSpan ts = new TimeSpan(4, 30, 0);
        Console.WriteLine(ts);
        Console.WriteLine(ts.Subtract(new TimeSpan(0, 15, 0)));
    }
}


TimeSpan.TicksPerDay

 
using System;
using System.Globalization;
class MainClass {
    public static void Main() {
        // Create some date/time objects
        DateTime dt = new DateTime();
        DateTime dt1 = new DateTime(2001, 12, 31);
        DateTime dt2 = new DateTime(2000, 12, 31, 23, 59, 59);
        // Do some date time math
        DateTime today = DateTime.Today;
        today = today + new TimeSpan(TimeSpan.TicksPerDay);
        Console.WriteLine("Tomorrow is: {0}", today.ToString());
        today = DateTime.Today - new TimeSpan(7 * TimeSpan.TicksPerDay);
        Console.WriteLine("Last Week on this day it was: {0}",today.ToString());
    }
}