├── tests
└── Aqua.DateTimeHelpers.Tests
│ ├── Aqua.DateTimeHelpers.Tests.csproj
│ └── DateTimeHelpersTests.cs
├── .github
└── workflows
│ └── dotnet-core.yml
├── src
├── Aqua.DateTimeHelpers
│ ├── Aqua.DateTimeHelpers.csproj
│ ├── LICENSE
│ └── DateTimeHelpers.cs
└── LICENSE
├── LICENSE
├── LICENSE.md
├── Aqua.DateTimeHelpers.sln
├── .gitignore
└── README.md
/tests/Aqua.DateTimeHelpers.Tests/Aqua.DateTimeHelpers.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 | false
7 |
8 |
9 |
10 |
11 | all
12 | runtime; build; native; contentfiles; analyzers; buildtransitive
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet-core.yml:
--------------------------------------------------------------------------------
1 | name: .NET Core
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | env:
10 | NUGET_SOURCE_URL: 'https://api.nuget.org/v3/index.json'
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Setup .NET Core
20 | uses: actions/setup-dotnet@v1
21 | with:
22 | dotnet-version: 3.1.301
23 | - name: Install dependencies
24 | run: dotnet restore
25 | - name: Build
26 | run: dotnet build --configuration Release --no-restore
27 | - name: Test
28 | run: dotnet test --no-restore --verbosity normal
29 | - name: 'Pack Project'
30 | run: dotnet pack --configuration Release
31 | - name: 'Push package'
32 | run: dotnet nuget push 'src/Aqua.StringHelpers/bin/Release/*.nupkg' -k ${{ secrets.NUGET_AUTH_TOKEN }} -s ${{ env.NUGET_SOURCE_URL }}
33 |
34 |
35 |
--------------------------------------------------------------------------------
/src/Aqua.DateTimeHelpers/Aqua.DateTimeHelpers.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | Is an Open Source and Free Software package to facilitate dealing with Date and Time, It supports all .NET Core versions as well as .NET Framework 4.6.1+
6 | Useme Alehosaini
7 |
8 | https://ualehosaini.github.io/aqua-date-time-helpers.html
9 | https://github.com/ualehosaini/Aqua.DateTimeHelpers
10 | git
11 | date time datetime helpers .net
12 | true
13 | snupkg
14 | LICENSE.md
15 | 1.0.1
16 |
17 |
18 |
19 |
20 | True
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Useme Alehosaini
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Useme Alehosaini
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Useme Alehosaini
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/Aqua.DateTimeHelpers/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Useme Alehosaini
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Aqua.DateTimeHelpers.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30611.23
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{032091C9-D941-40FB-A7EA-989DC013BD40}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{53CF0B62-009E-4092-83D0-410030EFD940}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "others", "others", "{85A275EC-77C0-4804-B6AB-ABD6052B51FF}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aqua.DateTimeHelpers", "src\Aqua.DateTimeHelpers\Aqua.DateTimeHelpers.csproj", "{C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aqua.DateTimeHelpers.Tests", "tests\Aqua.DateTimeHelpers.Tests\Aqua.DateTimeHelpers.Tests.csproj", "{44D4063B-3199-418D-BA58-63F0529196DF}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{DE459EC5-D016-43C7-8743-A4E05C0370DF}"
17 | EndProject
18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflow", "workflow", "{27D14E59-51B1-41D0-8913-EA8C9ECF0CD3}"
19 | EndProject
20 | Global
21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
22 | Debug|Any CPU = Debug|Any CPU
23 | Release|Any CPU = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
26 | {C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D}.Release|Any CPU.Build.0 = Release|Any CPU
30 | {44D4063B-3199-418D-BA58-63F0529196DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
31 | {44D4063B-3199-418D-BA58-63F0529196DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
32 | {44D4063B-3199-418D-BA58-63F0529196DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {44D4063B-3199-418D-BA58-63F0529196DF}.Release|Any CPU.Build.0 = Release|Any CPU
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | GlobalSection(NestedProjects) = preSolution
39 | {C0CA9359-DA8C-4C7D-B8CA-EB9D9306C20D} = {032091C9-D941-40FB-A7EA-989DC013BD40}
40 | {44D4063B-3199-418D-BA58-63F0529196DF} = {53CF0B62-009E-4092-83D0-410030EFD940}
41 | {27D14E59-51B1-41D0-8913-EA8C9ECF0CD3} = {DE459EC5-D016-43C7-8743-A4E05C0370DF}
42 | EndGlobalSection
43 | GlobalSection(ExtensibilityGlobals) = postSolution
44 | SolutionGuid = {2753340F-9747-4E29-900C-EEBC06263C44}
45 | EndGlobalSection
46 | EndGlobal
47 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 | /APOC.Backend.Api/Logs
332 |
--------------------------------------------------------------------------------
/src/Aqua.DateTimeHelpers/DateTimeHelpers.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Globalization;
4 | using System.Linq;
5 | using System.Threading;
6 |
7 | namespace Aqua.DateTimeHelpers
8 | {
9 | public static class DateTimeHelpers
10 | {
11 | private static readonly DateTime _epochDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
12 | private static readonly long _epochTicks = 621355968000000000L;
13 |
14 | ///
15 | /// Check the combination of Year, Month, and Day is a Valid Date
16 | ///
17 | ///
18 | ///
19 | ///
20 | ///
21 | public static bool IsValidDate(int year, int month, int day) => year >= DateTime.MinValue.Year &&
22 | year <= DateTime.MaxValue.Year &&
23 | month >= 1 &&
24 | month <= 12 &&
25 | day >= 1 &&
26 | DateTime.DaysInMonth(year, month) >= day;
27 |
28 | ///
29 | /// Check the combination of Hour, Minute, and Second is a Valid Time
30 | ///
31 | ///
32 | ///
33 | ///
34 | ///
35 | public static bool IsValidTime(int hour, int minute, int second = 0) => hour >= 0 &&
36 | hour <= 23 &&
37 | minute >= 0 &&
38 | minute <= 59 &&
39 | second >= 0 &&
40 | second <= 59;
41 |
42 | ///
43 | /// Check the combination of Year, Month, Day, Hour, Minute, and Second is a Valid DateTime
44 | ///
45 | ///
46 | ///
47 | ///
48 | ///
49 | ///
50 | ///
51 | ///
52 | public static bool IsValidDateTime(int year, int month, int day, int hour, int minute, int second = 0) => IsValidDate(year, month, day) &&
53 | IsValidTime(hour, minute, second);
54 |
55 | ///
56 | /// To Convert Unix
57 | /// Time Stamp To DateTime
58 | ///
59 | ///
60 | ///
61 | public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) => new DateTime(_epochDateTime.AddSeconds(unixTimeStamp).ToLocalTime().Ticks);
62 |
63 | ///
64 | /// To Convert Unix Time Stamp To DateTimeUTC
65 | ///
66 | ///
67 | ///
68 | public static DateTime UnixTimeStampToDateTimeUTC(double unixTimeStamp) => _epochDateTime.AddSeconds(unixTimeStamp);
69 |
70 | ///
71 | /// To Convert DateTime To Unix Time Stamp
72 | ///
73 | ///
74 | ///
75 | public static double DateTimeToUnixTimeStamp(DateTime dateTime) => (dateTime.ToUniversalTime().Ticks - _epochTicks) / TimeSpan.TicksPerSecond;
76 |
77 | ///
78 | /// Check the input if it is within a range of DateTime
79 | ///
80 | ///
81 | ///
82 | ///
83 | ///
84 | public static bool IsBetween(this DateTime input, DateTime rangeBegining, DateTime rangeEnd) => input.Ticks >= rangeBegining.Ticks &&
85 | input.Ticks < rangeEnd.Ticks;
86 |
87 | ///
88 | /// Returns the DateTime.MinValue
89 | ///
90 | ///
91 | public static DateTime GetMinDate() => DateTime.MinValue;
92 |
93 | ///
94 | /// Ignore Specific DateTime Part
95 | ///
96 | ///
97 | ///
98 | ///
99 | public static DateTime IgnoreTimeSpan(this DateTime dateTime, TimeSpan timeSpan)
100 | {
101 | if (timeSpan == TimeSpan.Zero)
102 | return dateTime;
103 |
104 | return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
105 | }
106 |
107 | ///
108 | /// Ignore the Milliseconds Part
109 | ///
110 | ///
111 | ///
112 | public static DateTime IgnoreMilliseconds(this DateTime dateTime) => dateTime.IgnoreTimeSpan(TimeSpan.FromMilliseconds(1000));
113 |
114 | ///
115 | /// Ignore the Seconds Part
116 | ///
117 | ///
118 | ///
119 | public static DateTime IgnoreSeconds(this DateTime dateTime) => dateTime.IgnoreTimeSpan(TimeSpan.FromSeconds(60));
120 |
121 | ///
122 | /// Ignore the Minutes Part
123 | ///
124 | ///
125 | ///
126 | public static DateTime IgnoreMinutes(this DateTime dateTime) => dateTime.IgnoreTimeSpan(TimeSpan.FromMinutes(60));
127 |
128 | ///
129 | /// Ignore the Hours Part
130 | ///
131 | ///
132 | ///
133 | public static DateTime IgnoreHours(this DateTime dateTime) => dateTime.IgnoreTimeSpan(TimeSpan.FromHours(24));
134 |
135 | ///
136 | /// Is The Date is Sunday?
137 | ///
138 | ///
139 | ///
140 | public static bool IsSunday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Sunday;
141 |
142 | ///
143 | /// Is The Date is Moday?
144 | ///
145 | ///
146 | ///
147 | public static bool IsMonday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Monday;
148 |
149 | ///
150 | /// Is The Date is Tuesday?
151 | ///
152 | ///
153 | ///
154 | public static bool IsTuesday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Tuesday;
155 |
156 | ///
157 | /// Is The Date is Wednesday?
158 | ///
159 | ///
160 | ///
161 | public static bool IsWednesday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Wednesday;
162 |
163 | ///
164 | /// Is The Date is Thursday?
165 | ///
166 | ///
167 | ///
168 | public static bool IsThursday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Thursday;
169 |
170 | ///
171 | /// Is The Date is Friday?
172 | ///
173 | ///
174 | ///
175 | public static bool IsFriday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Friday;
176 |
177 | ///
178 | /// Is The Date is Saturday?
179 | ///
180 | ///
181 | ///
182 | public static bool IsSaturday(this DateTime dateTime) => dateTime.DayOfWeek == DayOfWeek.Saturday;
183 |
184 | ///
185 | /// Last WeekDay in a Year / Month
186 | ///
187 | ///
188 | ///
189 | ///
190 | ///
191 | public static DateTime GetLastWeekdayOfMonth(int year, int month, DayOfWeek day)
192 | {
193 | DateTime lastDayOfTheMonth = new DateTime(year, month, 1)
194 | .AddMonths(1)
195 | .AddDays(-1);
196 | int searchDay = (int)day;
197 | int lastDay = (int)lastDayOfTheMonth.DayOfWeek;
198 | return lastDayOfTheMonth.AddDays(lastDay >= searchDay
199 | ? searchDay - lastDay
200 | : searchDay - lastDay - 7);
201 | }
202 |
203 | ///
204 | /// Generate Date List between two dates
205 | ///
206 | ///
207 | ///
208 | ///
209 | public static List GenerateDateList(DateTime fisrtDate, DateTime lastDate)
210 | {
211 | if (fisrtDate > lastDate)
212 | throw new ArgumentException("Incorrect last date " + lastDate);
213 |
214 | List result = new List();
215 | for (DateTime day = fisrtDate.Date; day.Date <= lastDate.Date; day = day.AddDays(1))
216 | {
217 | result.Add(day);
218 | }
219 |
220 | return result;
221 |
222 | }
223 |
224 | ///
225 | /// Return the Date of the first day of week of specific Date
226 | ///
227 | ///
228 | ///
229 | public static DateTime GetFirstDayOfWeek(DateTime dateTime)
230 | {
231 | CultureInfo culture = Thread.CurrentThread.CurrentCulture;
232 | int diff = dateTime.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
233 |
234 | if (diff < 0)
235 | {
236 | diff += 7;
237 | }
238 |
239 | return dateTime.AddDays(-diff).Date;
240 | }
241 |
242 | ///
243 | /// Return the Year's quarter number of specific date
244 | ///
245 | ///
246 | ///
247 | public static int QuarterOfYear(this DateTime dateTime)
248 | {
249 | return dateTime.Month >= 1 && dateTime.Month <= 3
250 | ? 1
251 | : dateTime.Month >= 4 && dateTime.Month <= 6
252 | ? 2
253 | : dateTime.Month >= 7 && dateTime.Month <= 9
254 | ? 3 : 4;
255 | }
256 |
257 | ///
258 | /// Returns Midnight of a DateTime
259 | ///
260 | ///
261 | ///
262 | public static DateTime Midnight(this DateTime dateTime) => dateTime.Date;
263 |
264 | ///
265 | /// Returns the age in years
266 | ///
267 | ///
268 | ///
269 | ///
270 | public static int AgeCalenderYears(DateTime referenceDate, DateTime today)
271 | {
272 | if (referenceDate > today)
273 | throw new ArgumentOutOfRangeException(nameof(referenceDate));
274 |
275 | return today.Year - referenceDate.Year;
276 | }
277 |
278 | ///
279 | /// Set a Time to a DateTime
280 | ///
281 | ///
282 | ///
283 | ///
284 | ///
285 | ///
286 | public static DateTime SetTime(this DateTime date, int hour = 0, int minute = 0, int second = 0)
287 | {
288 | if (!IsValidTime(hour, minute, second))
289 | throw new ArgumentOutOfRangeException("Time values are not within ccepted range");
290 | return new DateTime(date.Year, date.Month, date.Day, hour, minute, second);
291 | }
292 |
293 | ///
294 | /// Return the Date of the last day of week of specific Date
295 | ///
296 | ///
297 | ///
298 | public static DateTime GetLastDayOfWeek(DateTime dateTime) => GetFirstDayOfWeek(dateTime).AddDays(6);
299 |
300 | ///
301 | /// Return the Date of the first day of next week of specific Date
302 | ///
303 | ///
304 | ///
305 | public static DateTime GetFirstDayOfNextWeek(DateTime dateTime) => GetFirstDayOfWeek(dateTime).AddDays(7);
306 |
307 | ///
308 | /// Return the Date of the same day of next month
309 | ///
310 | ///
311 | ///
312 | public static DateTime NextMonthSameDay(this DateTime dateTime) => dateTime.AddMonths(1);
313 |
314 | ///
315 | /// Set a Day to a DateTime
316 | ///
317 | ///
318 | ///
319 | ///
320 | public static DateTime SetDay(this DateTime dateTime, int day)
321 | {
322 | if (!IsValidDate(dateTime.Year, dateTime.Month, day))
323 | throw new ArgumentOutOfRangeException(nameof(day));
324 |
325 | return dateTime.AddDays(-1 * dateTime.Day).AddDays(day);
326 |
327 | //return new DateTime(dateTime.Year, dateTime.Month, day, dateTime.Hour, dateTime.Minute, dateTime.Second);
328 | }
329 |
330 | ///
331 | /// Returns same DateTime as Next Year
332 | ///
333 | ///
334 | ///
335 | public static DateTime NextYearSameDay(this DateTime dateTime) => dateTime.AddYears(1);
336 |
337 | ///
338 | /// Returns Noon of a DateTime
339 | ///
340 | ///
341 | ///
342 | public static DateTime Noon(this DateTime dateTime) => dateTime.SetTime(12, 0, 0);
343 |
344 | ///
345 | /// Checks if The DateTime is an AM DateTime value
346 | ///
347 | ///
348 | ///
349 | public static bool IsDateAM(this DateTime dateTime) => dateTime >= dateTime.Midnight() && dateTime < dateTime.Noon();
350 |
351 | ///
352 | /// Return the Date of the same day of next week
353 | ///
354 | ///
355 | ///
356 | public static DateTime NextWeekSameDay(this DateTime dateTime) => dateTime.AddDays(7);
357 |
358 | ///
359 | /// Return the Year's week number of specific date
360 | ///
361 | ///
362 | ///
363 | public static int WeekOfYear(this DateTime dateTime)
364 | {
365 | int day = (int)dateTime.DayOfWeek;
366 | return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
367 | dateTime.AddDays(4 - (day == 0 ? 7 : day)),
368 | CalendarWeekRule.FirstFourDayWeek,
369 | DayOfWeek.Monday);
370 | }
371 |
372 | ///
373 | /// Set a Month to a DateTime
374 | ///
375 | ///
376 | ///
377 | ///
378 | public static DateTime SetMonth(this DateTime dateTime, int month)
379 | {
380 | if (!IsValidDate(dateTime.Year, month, dateTime.Day))
381 | throw new ArgumentOutOfRangeException("Either month value is not within the range or Month days became out of range");
382 |
383 | return dateTime.AddMonths(-1 * dateTime.Month).AddMonths(month);
384 | }
385 |
386 | ///
387 | /// Return the Date of the same day of previous week
388 | ///
389 | ///
390 | ///
391 | public static DateTime PreviousWeekSameDay(this DateTime dateTime) => dateTime.AddDays(-7);
392 |
393 | ///
394 | /// First WeekDay in a Year / Month
395 | ///
396 | ///
397 | ///
398 | ///
399 | ///
400 | public static DateTime GetFirstWeekdayOfMonth(int year, int month, DayOfWeek dayOfWeek)
401 | {
402 | return Enumerable.Range(1, 7).
403 | Select(day => new DateTime(year, month, day)).
404 | First(dateTime => (dateTime.DayOfWeek == dayOfWeek));
405 | }
406 |
407 | ///
408 | /// Returns same DateTime as Previous Year
409 | ///
410 | ///
411 | ///
412 | public static DateTime PreviousYearSameDay(this DateTime dateTime) => dateTime.AddYears(-1);
413 |
414 |
415 | ///
416 | /// Returns the age in years and months
417 | ///
418 | ///
419 | ///
420 | ///
421 | public static int AgeMonths(DateTime referenceDate, DateTime today)
422 | {
423 | if (referenceDate > today)
424 | throw new ArgumentOutOfRangeException(nameof(referenceDate));
425 |
426 | return (today.Year * 12 + today.Month) - (referenceDate.Year * 12 + referenceDate.Month);
427 | }
428 |
429 | ///
430 | /// Return the Date of the last day of previous week of specific Date
431 | ///
432 | ///
433 | ///
434 | public static DateTime GetLastDayOfPreviousWeek(DateTime dateTime) => GetFirstDayOfWeek(dateTime).AddDays(-1);
435 |
436 | ///
437 | /// Checks if The DateTime is an PM DateTime value
438 | ///
439 | ///
440 | ///
441 | public static bool IsDatePM(this DateTime dateTime) => dateTime >= dateTime.Noon() && dateTime < dateTime.AddDays(1).Midnight();
442 |
443 | ///
444 | /// Set a Year to a DateTime
445 | ///
446 | ///
447 | ///
448 | ///
449 | public static DateTime SetYear(this DateTime dateTime, int year)
450 | {
451 | if (!IsValidDate(year, dateTime.Month, dateTime.Day))
452 | throw new ArgumentOutOfRangeException(nameof(dateTime));
453 |
454 | return new DateTime(year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second)
455 | ;
456 | }
457 |
458 | ///
459 | /// Return the Date of the same day of previous week
460 | ///
461 | ///
462 | ///
463 | public static DateTime PreviousMonthSameDay(this DateTime dateTime) => dateTime.AddMonths(-1);
464 |
465 | ///
466 | /// Returns the age's exact number of years- calulatedfrom exact months
467 | ///
468 | ///
469 | ///
470 | ///
471 | public static decimal AgeExactYears(DateTime referenceDate, DateTime today)
472 | {
473 | if (referenceDate > today)
474 | throw new ArgumentOutOfRangeException(nameof(referenceDate));
475 |
476 | return Math.Round(((decimal)(today.Year * 12 + today.Month) - (referenceDate.Year * 12 + referenceDate.Month)) / 12, 2);
477 | }
478 |
479 | ///
480 | /// Generate a List of BusinessDays with considering
481 | /// Local Weekend Days Sequence (entered s list)
482 | /// and national holidays (entered as list)
483 | ///
484 | ///
485 | ///
486 | ///
487 | /// Sunday = 0 .. Satuday = 6
488 | ///
489 | public static IEnumerable GenerateBusinessDaysList(DateTime fisrtDate, DateTime lastDate, List holidays, List weekends)
490 | {
491 | if (fisrtDate > lastDate)
492 | throw new ArgumentException("Incorrect last date " + lastDate);
493 |
494 | List result = GenerateDateList(fisrtDate, lastDate);
495 |
496 | foreach (int d in weekends)
497 | {
498 | for (int i = 0; i < result.Count; i++)
499 | {
500 | if ((int)result[i].DayOfWeek == d)
501 | {
502 | result.RemoveAt(i);
503 | }
504 | }
505 | }
506 |
507 | foreach (DateTime d in holidays)
508 | {
509 | for (int i = 0; i < result.Count; i++)
510 | {
511 | if (result[i] == d)
512 | {
513 | result.RemoveAt(i);
514 | }
515 | }
516 | }
517 |
518 | return result.OrderBy(d => d.Date);
519 | }
520 |
521 | ///
522 | /// Returns the DateTime.MaxValue
523 | ///
524 | ///
525 | public static DateTime GetMaxDate() => DateTime.MaxValue;
526 |
527 | }
528 | }
529 |
--------------------------------------------------------------------------------
/tests/Aqua.DateTimeHelpers.Tests/DateTimeHelpersTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using Xunit;
4 |
5 | namespace Aqua.DateTimeHelpers.Tests
6 | {
7 | public class DateTimeHelpersTests
8 | {
9 | [Theory]
10 | [InlineData(true, 2017, 1, 1)]
11 | [InlineData(false, 2017, 10, 35)]
12 | [InlineData(false, 2017, 13, 1)]
13 | public void IsValidDate_Valid(bool expected,
14 | int year,
15 | int month,
16 | int day) => Assert.Equal(expected, DateTimeHelpers.IsValidDate(year, month, day));
17 |
18 | [Theory]
19 | [InlineData(true, 23, 30)]
20 | [InlineData(true, 23, 30, 10)]
21 | [InlineData(false, 25, 30, 10)]
22 | [InlineData(false, 23, 65, 10)]
23 | [InlineData(false, 23, 30, 65)]
24 | public void IsValidTime_Valid(bool expected,
25 | int hour,
26 | int minute,
27 | int second = 0) => Assert.Equal(expected, DateTimeHelpers.IsValidTime(hour, minute, second));
28 |
29 | [Theory]
30 | [InlineData(true, 2017, 1, 1, 22, 30)]
31 | [InlineData(true, 2017, 1, 1, 22, 30, 10)]
32 | [InlineData(false, 2017, 1, 1, 22, 30, 65)]
33 | [InlineData(false, 2017, 10, 35, 10, 10, 10)]
34 | [InlineData(false, 2017, 13, 1, 25, 25, 10)]
35 | public void IsValidDateTime_Valid(bool expected,
36 | int year,
37 | int month,
38 | int day,
39 | int hour,
40 | int minute,
41 | int second = 0) => Assert.Equal(expected, DateTimeHelpers.IsValidDateTime(year, month, day, hour, minute, second));
42 |
43 | [Theory]
44 | [InlineData(0, 1970, 1, 1, 0, 0, 0)]
45 | [InlineData(86399, 1970, 1, 1, 23, 59, 59)]
46 | [InlineData(1444471810, 2015, 10, 10, 10, 10, 10)]
47 | [InlineData(1433592775, 2015, 6, 6, 12, 12, 55)]
48 | public void UnixTimeStampToDateTime_Valid(long input,
49 | int y,
50 | int m,
51 | int d,
52 | int h,
53 | int mnt,
54 | int s)
55 | {
56 | DateTime mid = new DateTime(y, m, d, h, mnt, s, DateTimeKind.Utc);
57 | DateTime expected = new DateTime(mid.ToLocalTime().Ticks);
58 |
59 | Assert.Equal(expected, DateTimeHelpers.UnixTimeStampToDateTime(input));
60 | }
61 |
62 | [Theory]
63 | [InlineData(0, 1970, 1, 1, 0, 0, 0)]
64 | [InlineData(86399, 1970, 1, 1, 23, 59, 59)]
65 | [InlineData(1444471810, 2015, 10, 10, 10, 10, 10)]
66 | [InlineData(1433592775, 2015, 6, 6, 12, 12, 55)]
67 | public void UnixTimeStampToDateTimeUTC_Valid(long input,
68 | int y,
69 | int m,
70 | int d,
71 | int h,
72 | int mnt,
73 | int s)
74 | {
75 | DateTime expected = new DateTime(y, m, d, h, mnt, s, DateTimeKind.Utc);
76 |
77 | Assert.Equal(expected, DateTimeHelpers.UnixTimeStampToDateTimeUTC(input));
78 | }
79 |
80 | [Theory]
81 | [InlineData(0, 1970, 1, 1, 0, 0, 0)]
82 | [InlineData(86399, 1970, 1, 1, 23, 59, 59)]
83 | [InlineData(1444471810, 2015, 10, 10, 10, 10, 10)]
84 | [InlineData(1433592775, 2015, 6, 6, 12, 12, 55)]
85 | public void DateTimeToUnixTimeStamp_Valid(long expected,
86 | int y,
87 | int m,
88 | int d,
89 | int h,
90 | int mnt,
91 | int s)
92 | {
93 | DateTime value = new DateTime(y, m, d, h, mnt, s, DateTimeKind.Utc);
94 |
95 | Assert.Equal(expected, DateTimeHelpers.DateTimeToUnixTimeStamp(value));
96 | }
97 |
98 | [Theory]
99 | [MemberData(nameof(IsBetweenData))]
100 | public void IsBetween_Valid(bool expected,
101 | DateTime input,
102 | DateTime rangeBegining,
103 | DateTime rangeEnd) => Assert.Equal(expected, input.IsBetween(rangeBegining, rangeEnd));
104 |
105 | public static IEnumerable