Skip to content

karenpayneoregon/dataonly-timeonly

Repository files navigation

Working with DateOnly and TimeOnly (C#)

This repository demonstrates simple usage of DateOnly Struct done with a prerelease product.

There is a class project which is responsible for reading a json file with type Person class into a list using System.Text.Json. JsonSerializer.Deserialize. In the unit test project this data is tested as instances of the Person class.

Extension

To convert a DateOnly variable to a DateTime we use ToDateTime which requires a TimeOnly so to keep code light here is a lazy extension which default to mid-night or allows changing hours and/or minutes.

public static DateTime ToDateTime(this DateOnly sender, int hour = 0, int minutes = 0)
    => sender.ToDateTime(new TimeOnly(hour, minutes));

Remarks

  • File scoped namespaces feature from C# 10 won't work
  • To use DateOnly and TimeOnly install SDK 6x
  • If using VS2019 for desktop projects
    • Set Use previews as shown in the image below
    • Set TargetFramework to net6.0-windows
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
	  <LangVersion>9.0</LangVersion>
	  <TargetFramework>net6.0-windows</TargetFramework>
  </PropertyGroup>

</Project>
  • Currently no code samples for TimeOnly which will follow shortly.

See also

img

About

Basic code samples for DateOnly and TimeOnly

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages