Visit the gigasecond exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Use AddSeconds
AddSeconds
using System;
public static class Gigasecond
{
public static DateTime Add(DateTime birthDate)
{
return birthDate.AddSeconds(1_000_000_000);
}
}
The DateTime class has an AddSeconds() method that takes the number of seconds to add to the DateTime instance.
We then simply pass in the gigasecond value and a new DateTime instance is returned with the amount of seconds specified added to it.
Shortening
There are two things we can do to further shorten this method:
- Remove the curly braces by converting to an expression-bodied method
- Replace
1_000_000_000 with 1e9, which is the same number but in scientific notation
Using this, we end up with:
public static DateTime Add(DateTime birthDate) => birthDate.AddSeconds(1e9);
Use a TimeSpan
TimeSpan
using System;
public static class Gigasecond
{
public static DateTime Add(DateTime birthDate)
{
return birthDate + TimeSpan.FromSeconds(1_000_000_000);
}
}
The DateTime class supports adding a TimeSpan instance via the + operator.
We then simply use the + operator on the DateTime instance and pass it the gigasecond in the form of a TimeSpan by using its TimeSpan.FromSeconds() factory method.
This will return a new DateTime instance with the amount of seconds represented by the TimeSpan added to it.
Shortening
There are two things we can do to further shorten this method:
- Remove the curly braces by converting to an expression-bodied method
- Replace
1_000_000_000 with 1e9, which is the same number but in scientific notation
Using this, we end up with:
public static DateTime Add(DateTime birthDate) => birthDate + TimeSpan.FromSeconds(1e9);
Source: Exercism csharp/gigasecond