diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 0000000..370db06 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "automerge": true, + "prHourlyLimit": 0, + "autoApprove": true +} diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml new file mode 100644 index 0000000..89c873a --- /dev/null +++ b/.github/workflows/automerge.yml @@ -0,0 +1,24 @@ +name: automerge +on: pull_request + +permissions: + contents: write + pull-requests: write + +env: + GH_TOKEN: ${{ secrets.RENOVATEBOT }} + +jobs: + automerge: + runs-on: ubuntu-latest + if: ${{ github.actor == 'renovate[bot]' }} + steps: + - name: Enable auto-merge for Renovate PRs + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + + - name: Approve patch and minor updates + run: gh pr review $PR_URL --approve + env: + PR_URL: ${{github.event.pull_request.html_url}} diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 0000000..d0bc641 --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,33 @@ +name: build-and-test +on: + # Testing - run for any PRs. + pull_request: + branches: + - main + +env: + "PipelineEnvironment": true + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET 8.0 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install dependencies + run: dotnet restore + + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test test/Soenneker.Extensions.DateTime.Quarter.Tests.csproj --no-restore --verbosity normal + + - name: Pack + run: dotnet pack --no-build --configuration Release --output . diff --git a/.github/workflows/publish-package.yml b/.github/workflows/publish-package.yml new file mode 100644 index 0000000..9bee655 --- /dev/null +++ b/.github/workflows/publish-package.yml @@ -0,0 +1,45 @@ +name: publish-package +on: + push: + branches: + - main + + # Publish `v1.2.3` tags as releases. + tags: + - v* + +env: + "PipelineEnvironment": true + +jobs: + publish-package: + runs-on: ubuntu-latest + +#{Services} + steps: + - uses: actions/checkout@v4 + + - name: Setting up build version + run: | + version=$(($GITHUB_RUN_NUMBER)) + echo "BUILD_VERSION=2.1.$version" >> ${GITHUB_ENV} + + - name: Setup .NET Core 8.0 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install dependencies + run: dotnet restore + + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test test/Soenneker.Extensions.DateTime.Quarter.Tests.csproj --no-restore --verbosity normal + + - name: Pack + run: dotnet pack --no-build --configuration Release --output . + + - name: Publish to nuGet + run: dotnet nuget push **\*.nupkg --source 'https://api.nuget.org/v3/index.json' --api-key ${{secrets.NUGET_TOKEN}} --skip-duplicate diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1ee5385 --- /dev/null +++ b/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..2c37cb5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# Contributing to Soenneker.Extensions.DateTime.Quarter + +We're excited that you're interested in contributing! + +## How to Contribute + +1. **Create an Issue** + - If you have a new feature idea, a bug report, or any other improvement suggestion, start by creating an issue on the [Issues](https://github.com/soenneker/soenneker.extensions.datetime.quarter/issues) page. + - Clearly describe the problem or enhancement you're proposing and provide as much detail as possible. + +1. **Fork the Repository** + - If you want to work on a feature or bug fix, fork the repository's `main` branch to your GitHub account. + +1. **Create a Branch** + - Create a new branch for your contribution. Use a descriptive name that reflects the purpose of your changes. + +1. **Make Changes** + - If you've changed APIs, update the documentation. + - If you've added code that should be tested, add tests. + - Be sure to follow the coding conventions and guidelines of the project. + +1. **Test Your Changes** + - Test your changes thoroughly to ensure that they work as expected. + +1. **Commit Changes** + - Commit your changes with a clear and concise commit message. + +1. **Push Changes** + - Push your changes to your forked repository on GitHub. + +1. **Create a Pull Request** + - Go to the [Pull Requests](https://github.com/soenneker/soenneker.extensions.datetime.quarter/pulls) page of the original repository. + - Click on "New Pull Request." + - Select your forked repository and the branch with your changes. + - Provide a clear title and description. Include the link of the original issue. + +1. **Code Review** + - Your pull request will be reviewed by the maintainers. + - Be responsive to any feedback and make necessary changes. + - Once your pull request is approved, it will be merged into the main branch. + +## Sponsor us + +If you don't have the time or expertise to contribute code, you can still support us by [sponsoring](https://github.com/sponsors/soenneker). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7d4bbc2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jake Soenneker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index b4b7c4c..6b636dc 100644 --- a/README.md +++ b/README.md @@ -1 +1,12 @@ -Standby... \ No newline at end of file +[![](https://img.shields.io/nuget/v/soenneker.extensions.datetime.quarter.svg?style=for-the-badge)](https://www.nuget.org/packages/soenneker.extensions.datetime.quarter/) +[![](https://img.shields.io/github/actions/workflow/status/soenneker/soenneker.extensions.datetime.quarter/publish-package.yml?style=for-the-badge)](https://github.com/soenneker/soenneker.extensions.datetime.quarter/actions/workflows/publish-package.yml) +[![](https://img.shields.io/nuget/dt/soenneker.extensions.datetime.quarter.svg?style=for-the-badge)](https://www.nuget.org/packages/soenneker.extensions.datetime.quarter/) + +# ![](https://user-images.githubusercontent.com/4441470/224455560-91ed3ee7-f510-4041-a8d2-3fc093025112.png) Soenneker.Extensions.DateTime.Quarter +### A collection of helpful DateTime quarter (year) based extension methods + +## Installation + +``` +dotnet add package Soenneker.Extensions.DateTime.Quarter +``` diff --git a/Soenneker.Extensions.DateTime.Quarter.sln b/Soenneker.Extensions.DateTime.Quarter.sln new file mode 100644 index 0000000..d801958 --- /dev/null +++ b/Soenneker.Extensions.DateTime.Quarter.sln @@ -0,0 +1,46 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33209.295 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Soenneker.Extensions.DateTime.Quarter", "src\Soenneker.Extensions.DateTime.Quarter.csproj", "{41850636-33B4-4228-AE59-A2113F66B9FA}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{4E42254D-039C-40ED-B3F4-8C1A94A366D1}" + ProjectSection(SolutionItems) = preProject + .github\renovate.json = .github\renovate.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{D786EC1A-4F59-412F-8624-83E6E3525B0C}" + ProjectSection(SolutionItems) = preProject + .github\workflows\automerge.yml = .github\workflows\automerge.yml + .github\workflows\build-and-test.yml = .github\workflows\build-and-test.yml + .github\workflows\publish-package.yml = .github\workflows\publish-package.yml + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Soenneker.Extensions.DateTime.Quarter.Tests", "test\Soenneker.Extensions.DateTime.Quarter.Tests.csproj", "{6456E465-9523-4612-9115-9D9B585B42E8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {41850636-33B4-4228-AE59-A2113F66B9FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Release|Any CPU.Build.0 = Release|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {D786EC1A-4F59-412F-8624-83E6E3525B0C} = {4E42254D-039C-40ED-B3F4-8C1A94A366D1} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B849EC5C-B7B3-4C90-9B66-CBC15CCB776A} + EndGlobalSection +EndGlobal diff --git a/Soenneker.Extensions.DateTime.Quarter.sln.DotSettings b/Soenneker.Extensions.DateTime.Quarter.sln.DotSettings new file mode 100644 index 0000000..ca6ccef --- /dev/null +++ b/Soenneker.Extensions.DateTime.Quarter.sln.DotSettings @@ -0,0 +1,25 @@ + + False + 0 + 0 + NEVER + NEVER + + True + True + UseVarWhenEvident + UseVarWhenEvident + UseVarWhenEvident + ML + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + True + True + True + True + True + 9999 + True + diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..1324943 Binary files /dev/null and b/icon.png differ diff --git a/src/DateTimeQuarterExtension.cs b/src/DateTimeQuarterExtension.cs new file mode 100644 index 0000000..48d00a7 --- /dev/null +++ b/src/DateTimeQuarterExtension.cs @@ -0,0 +1,112 @@ +using System.Diagnostics.Contracts; +using Soenneker.Enums.DateTimePrecision; + +namespace Soenneker.Extensions.DateTime.Quarter; + +/// +/// Provides extension methods for to handle quarter calculations. +/// +public static class DateTimeQuarterExtension +{ + /// + /// Adjusts the specified to the start of its quarter. + /// + /// The date and time to adjust. + /// A representing the first moment of the quarter. + [Pure] + public static System.DateTime ToStartOfQuarter(this System.DateTime dateTime) + { + System.DateTime result = dateTime.ToStartOf(DateTimePrecision.Quarter); + return result; + } + + /// + /// Adjusts the specified to the end of its quarter. + /// + /// The date and time to adjust. + /// A representing the last moment of the quarter. + [Pure] + public static System.DateTime ToEndOfQuarter(this System.DateTime dateTime) + { + System.DateTime result = dateTime.ToEndOf(DateTimePrecision.Quarter); + return result; + } + + /// + /// Adjusts the specified UTC , converted to the time zone specified by , to the start of the previous quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the first moment of the previous quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToStartOfTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToTz(tzInfo).ToStartOfQuarter().ToUtc(tzInfo); + return start; + } + + /// + /// Converts the specified UTC to the time zone specified by , and adjusts it to the end of its quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the last moment of the quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToStartOfNextTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToStartOfTzQuarter(tzInfo).AddMonths(3); + return start; + } + + /// + /// Adjusts the specified UTC , converted to the time zone specified by , to the start of the previous quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the first moment of the previous quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToStartOfPreviousTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToStartOfTzQuarter(tzInfo).AddMonths(-3); + return start; + } + + /// + /// Converts the specified UTC to the time zone specified by , and adjusts it to the end of its quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the last moment of the quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToEndOfTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToTz(tzInfo).ToEndOfQuarter().ToUtc(tzInfo); + return start; + } + + /// + /// Adjusts the specified UTC , converted to the time zone specified by , to the end of the next quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the last moment of the next quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToEndOfNextTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToEndOfTzQuarter(tzInfo).AddMonths(3); + return start; + } + + /// + /// Adjusts the specified UTC , converted to the time zone specified by , to the end of the previous quarter in that time zone. + /// + /// The UTC date and time to convert and adjust. + /// The time zone to convert to. + /// A representing the last moment of the previous quarter in UTC, adjusted for the specified time zone. + [Pure] + public static System.DateTime ToEndOfPreviousTzQuarter(this System.DateTime utcNow, System.TimeZoneInfo tzInfo) + { + System.DateTime start = utcNow.ToEndOfTzQuarter(tzInfo).AddMonths(-3); + return start; + } +} diff --git a/src/Soenneker.Extensions.DateTime.Quarter.csproj b/src/Soenneker.Extensions.DateTime.Quarter.csproj new file mode 100644 index 0000000..64d27fb --- /dev/null +++ b/src/Soenneker.Extensions.DateTime.Quarter.csproj @@ -0,0 +1,47 @@ + + + + netstandard2.1 + enable + AnyCPU + $(NoWarn);1591 + + + + A collection of helpful DateTime quarter (year) based extension methods + 2.1.0 + $(BUILD_VERSION) + Soenneker.Extensions.DateTime.Quarter + Soenneker.Extensions.DateTime.Quarter + extensions datetime quarter timezone date time zone month conversion datetimequarterextension extension csharp dotnet c# .net + Copyright © 2024 Jake Soenneker + Jake Soenneker + https://soenneker.com + true + true + true + snupkg + true + MIT + https://github.com/soenneker/soenneker.extensions.datetime.quarter + https://github.com/soenneker/soenneker.extensions.datetime.quarter + git + main + false + true + latest + README.md + icon.png + + + + + + + + + + + + + diff --git a/test/DateTimeQuarterExtensionTests.cs b/test/DateTimeQuarterExtensionTests.cs new file mode 100644 index 0000000..63356c7 --- /dev/null +++ b/test/DateTimeQuarterExtensionTests.cs @@ -0,0 +1,42 @@ +using FluentAssertions; +using Soenneker.Tests.Unit; +using System; +using Xunit; + +namespace Soenneker.Extensions.DateTime.Quarter.Tests; + +public class DateTimeQuarterExtensionTests : UnitTest +{ + [Theory] + [InlineData("2023-01-15", "2023-01-01")] + [InlineData("2023-04-01", "2023-04-01")] + [InlineData("2023-12-31", "2023-10-01")] + public void ToStartOfQuarter_Should_CorrectlyCalculateStartOfQuarter(string inputDate, string expectedDate) + { + // Arrange + System.DateTime dateTime = System.DateTime.Parse(inputDate); + + // Act + System.DateTime result = DateTimeQuarterExtension.ToStartOfQuarter(dateTime); + + // Assert + result.Should().Be(System.DateTime.Parse(expectedDate)); + } + + [Theory] + [InlineData("2023-01-15", "2023-03-31 23:59:59.9999999")] + [InlineData("2023-04-01", "2023-06-30 23:59:59.9999999")] + [InlineData("2023-12-31", "2023-12-31 23:59:59.9999999")] + public void ToEndOfQuarter_Should_CorrectlyCalculateEndOfQuarter(string inputDate, string expectedDateString) + { + // Arrange + System.DateTime dateTime = System.DateTime.Parse(inputDate); + System.DateTime expectedDate = System.DateTime.ParseExact(expectedDateString, "yyyy-MM-dd HH:mm:ss.fffffff", null); + + // Act + System.DateTime result = DateTimeQuarterExtension.ToEndOfQuarter(dateTime); + + // Assert + result.Should().BeCloseTo(expectedDate, TimeSpan.FromMilliseconds(1)); + } +} diff --git a/test/Soenneker.Extensions.DateTime.Quarter.Tests.csproj b/test/Soenneker.Extensions.DateTime.Quarter.Tests.csproj new file mode 100644 index 0000000..bad4f18 --- /dev/null +++ b/test/Soenneker.Extensions.DateTime.Quarter.Tests.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + enable + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + +