https://github.com/karenpayneoregon/dataonly-timeonly
Basic code samples for DateOnly and TimeOnly
https://github.com/karenpayneoregon/dataonly-timeonly
csharp dateonly netcore6 timeonly
Last synced: 17 days ago
JSON representation
Basic code samples for DateOnly and TimeOnly
- Host: GitHub
- URL: https://github.com/karenpayneoregon/dataonly-timeonly
- Owner: karenpayneoregon
- Created: 2021-10-03T23:13:07.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-12-27T15:11:28.000Z (over 2 years ago)
- Last Synced: 2025-04-01T05:41:25.432Z (about 2 months ago)
- Topics: csharp, dateonly, netcore6, timeonly
- Language: C#
- Homepage:
- Size: 211 KB
- Stars: 3
- Watchers: 1
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# Working with DateOnly and TimeOnly (C#)
This repository demonstrates simple usage of [DateOnly Struct](https://docs.microsoft.com/en-us/dotnet/api/system.dateonly?view=net-6.0) done with a prerelease product.
There is a [class project](https://github.com/karenpayneoregon/dataonly-timeonly/blob/master/FileLibrary/Classes/Operations.cs) which is responsible for reading a json file with type Person class into a list using [System.Text.Json. JsonSerializer.Deserialize](https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=net-5.0). 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](https://github.com/karenpayneoregon/dataonly-timeonly/blob/master/FileLibrary/LanguageExtensions/DateOnlyExtensions.cs) which default to mid-night or allows changing hours and/or minutes.
```charp
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](https://dotnet.microsoft.com/download/dotnet/6.0?WT.mc_id=DT-MVP-5002866)
- If using `VS2019` for desktop projects
- Set Use previews as shown in the image below
- Set `TargetFramework` to `net6.0-windows````xml
9.0
net6.0-windows
```
- Currently no code samples for [TimeOnly](https://docs.microsoft.com/en-us/dotnet/api/system.timeonly?view=net-6.0) which will follow shortly.
## See also
- [Developers can benefit from enhanced Date and Time types and Timezone support](https://github.com/dotnet/runtime/issues/45318)
- NodaTime [ZonedDateTime](https://nodatime.org/2.4.x/api/NodaTime.ZonedDateTime.html)