TimeSpan add and subtract
In this chapter you will learn:
- How to add time span to another time span
- How to subtract from time span
- Subtract 15 minutes from the current TimeSpan and print the result
Add to TimeSpan
using System;/*from j a v a2 s . com*/
class MainClas
{
public static void Main()
{
TimeSpan myTimeSpan13 = new TimeSpan(1, 10, 13);
TimeSpan myTimeSpan14 = new TimeSpan(2, 6, 10);
TimeSpan myTimeSpan15 = myTimeSpan13.Add(myTimeSpan14);
Console.WriteLine("myTimeSpan13 = " + myTimeSpan13);
Console.WriteLine("myTimeSpan14 = " + myTimeSpan14);
Console.WriteLine("myTimeSpan15 = " + myTimeSpan15);
}
}
Subtract from TimeSpan
using System;//from j a v a 2 s. co m
class MainClas
{
public static void Main()
{
TimeSpan myTimeSpan13 = new TimeSpan(1, 10, 13);
TimeSpan myTimeSpan14 = new TimeSpan(2, 6, 10);
TimeSpan myTimeSpan15 = myTimeSpan13.Subtract(myTimeSpan14);
Console.WriteLine("myTimeSpan15 = " + myTimeSpan15);
}
}
Subtract 15 minutes
using System;/*from j a va 2s .c o m*/
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)));
}
}
Next chapter...
What you will learn in the next chapter:
- Calculation based on the TimeSpan
- Subtract one DateTime from another you get a TimeSpan
- Use the Add() method to add a TimeSpan to a DateTime
- Use the Subtract() method to subtract a TimeSpan from a DateTime
Home » C# Tutorial » Date, Time, TimeZone