Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use TimeOnly and DateOnly in .NET Framework 4.8

Tags:

c#

.net-4.8

I't doesn't matter what code I post because .NET 6 has TimeOnly and DateOnly. Is there a way I can use it in .NET Framework 4.8? Can I add a reference somewhere or is it not possible to be able to use DateOnly and TimeOnly.

Here is the code that I wrote in .NET 6 and now want to use in .NET Framework 4.8

public TimeOnly Time = new TimeOnly();
public DateOnly Date = new DateOnly();

This is the error

like image 982
Johan Avatar asked Dec 15 '25 04:12

Johan


2 Answers

Those types exist out of the box only in .Net 6+, so they are not available in older versions.

However, you can add them manually. For example, using this NuGet: https://www.nuget.org/packages/Portable.System.DateTimeOnly

It will add those types to your .Net Framework projects, and they should behave relatively the same as .Net 6 ones (see more info in NuGet's description).

like image 67
maxc137 Avatar answered Dec 16 '25 22:12

maxc137


Unfortunately, it's not possible to use TimeOnly and DateOnly types on .NET Framework. Those types were introduced in .NET 6 and will not be backported on .NET Framework.

Some time ago, I tried to compile them for .NET Standard (which would make them available on .NET Framework) but as expected, it was a huge amount of work because their implementation depends on many types which are also only available on .NET 6. While this would probably be technically possible, it's definitely not worth the effort.

I can think of two solutions for you.

  1. Migrate your .NET Framework 4.8 app to .NET 6
  2. Take a dependency on NodaTime and use the equivalent LocalTime and LocalDate types instead
like image 35
0xced Avatar answered Dec 16 '25 22:12

0xced



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!