public static class Disposable {
public static TResult Using<TDisposable,TResult>(
Func<TDisposable> factory,
Func<TDisposable, TResult> map)
where TDisposable : IDisposable
{
using (var disposable = factory()){
return map(disposable);
}
}
}
void Main()
{
var currentTime = EpochTime.AddSeconds(Disposable
.Using(() => new HttpClient(),
client => JsonDocument.Parse(client.GetStringAsync(@"http://worldtimeapi.org/api/timezone/europe/oslo").Result))
.RootElement
.GetProperty("unixtime")
.GetInt64()).ToLocalTime(); //list of time zones available here: http://worldtimeapi.org/api/timezone
currentTime.Dump("CurrentTime");
}
public static DateTime EpochTime => new DateTime(1970, 1, 1);
The Disposable is abstracted away in the helper method called Using accepting a factory function to create a TDisposable that accepts an IDisposable.
We look up the current time using the WorldTimeApi and make use of extracting the UnixTime which is measured from Epoch as the number of seconds elapsed from 1st January 1970.
We make use of System.Text.Json here, which is part of .NET to parse the json retrieved.
Saturday, 9 March 2024
Functional programming - looking up current time and encapsulating usings
I looked at encapsulating Using statements today for functional programming and how to look up the current time with API available on the Internet.
No comments:
Post a Comment