Converting DateOnly and TimeOnly to DateTime and vice versa in .NET 6
Since I have introduced DateOnly and TimeOnly feature of .NET 6 in my previous article( Simplified Date and Time with DateOnly and TimeOnly types in .NET 6), I have got some query related to compatibility with DateTime like,
How DateOnly and TimeOnly can be used with legacy application where DateTime is already used?
How can we migrate to use this ?
How do we interact with external interface which are still using DateTime ?
Don’t worry .NET developers already thought of it and they have provided the proper methods to do the conversion.
Let’s look at the example.
Converting DateTime to DateOnly
// Creating DateTime object
DateTime testDateTime = new DateTime(2021,09,21);// Creating DateOnly object from DateTime.
DateOnly testDateOnly = DateOnly.FromDateTime(testDateTime);Console.WriteLine(testDateOnly.ToString());//Output -> 09/21/2021
Converting DateTime to TimeOnly
// Creating DateTime object
DateTime testDateTime = new DateTime(2021,09,21,03,13,22);// Creating TimeOnly object from DateTime.
TimeOnly testTimeOnly = TimeOnly.FromDateTime(testDateTime);Console.WriteLine(testTimeOnly.ToLongTimeString());//Output -> 03:13:22
Converting DateOnly to DateTime
// Creating DateOnly instance
DateOnly dateOnly = new DateOnly(2021, 9, 16);// Converting DateOnly to DateTime by providing Time Info
DateTime testDateTime = dateOnly.ToDateTime(TimeOnly.Parse("10:00 PM"));Console.WriteLine(testDateTime);//Output -> 09/16/2021 22:00:00
As you can see, to convert from DateOnly to DateTime, we need to provide TimeOnly info along with it.
we can provide actual time or we can provide TimeOnly.MinValue to specify the midnight where time is not “relevant”.
Converting TimeOnly to DateTime
This is little tricky, if you think there are no scenario where you would be converting TimeOnly to DateTime, even if you have to then it would be same as we already did above in Converting DateOnly to DateTime section.
But it support to convert the TimeOnly to TimeSpan.
Let’s look at the example.
Converting TimeOnly to TimeSpan
//Creating TimeOnly instance
TimeOnly timeOnly = TimeOnly.Parse("10:00 PM");// Converting TimeOnly to TimeSpan
TimeSpan timeSpan = timeOnly.ToTimeSpan();Console.WriteLine(timeSpan);//Output -> 22:00:00
Summary
Converting DateTime to DateOnly and TimeOnly is very easy and simple and already well supported in library itself.
Hope it is useful.
Thanks for reading..!
Happy coding..!
If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.