How to get days, hours, minutes, seconds from DateTime as a decimal?MyISAM versus InnoDBHow to return only the Date from a SQL Server DateTime datatypeHow to round a number to n decimal places in JavaHow do I get current datetime on the Windows command line, in a suitable format for using in a filename?How do you get a timestamp in JavaScript?How to get the current time in PythonGet int value from enum in C#Best approach to remove time part of datetime in SQL ServerImprove INSERT-per-second performance of SQLite?How to make an unaware datetime timezone aware in python
My colleague treats me like he's my boss, yet we're on the same level
Why does Sauron not permit his followers to use his name?
Sandwich Sudoku: First 12 digits of pi
Are sweatpants frowned upon on flights?
Does the telecom provider need physical access to the SIM card to clone it?
GPL Licensed Woocommerce paid plugins
What caused the end of cybernetic implants?
In what language did Túrin converse with Mím?
In Endgame, wouldn't Stark have remembered Hulk busting out of the stairwell?
German equivalent to "going down the rabbit hole"
What checks exist against overuse of presidential pardons in the USA?
Group riding etiquette
Was a six-engine 747 ever seriously considered by Boeing?
Strange behavior of std::initializer_list of std::strings
What am I looking at here at Google Sky?
“all of who” or “all of whom”?
Under GDPR, can I give permission once to allow everyone to store and process my data?
Why do IR remotes influence AM radios?
How do I get my neighbour to stop disturbing with loud music?
What is the practical impact of using System.Random which is not cryptographically random?
'spazieren' - walking in a silly and affected manner?
Lob Logical Read and lob read-ahead reads in NCCI
When is it a good idea to capture the fianchettoed bishop?
How to investigate an unknown 1.5GB file named "sudo" in my Linux home directory?
How to get days, hours, minutes, seconds from DateTime as a decimal?
MyISAM versus InnoDBHow to return only the Date from a SQL Server DateTime datatypeHow to round a number to n decimal places in JavaHow do I get current datetime on the Windows command line, in a suitable format for using in a filename?How do you get a timestamp in JavaScript?How to get the current time in PythonGet int value from enum in C#Best approach to remove time part of datetime in SQL ServerImprove INSERT-per-second performance of SQLite?How to make an unaware datetime timezone aware in python
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a DateTime
and need to get the days and hours in a decimal format. For example, for new DateTime(2009, 6, 19, 18, 0, 0);
I need the days as 19.75
. Day + (TimeOfDay.TotalHours / 24)
seems to work but is there a straight or better conversion? Speed is important for this calculation considering I'm also using high-resolution dates.
c# performance datetime decimal
add a comment |
I have a DateTime
and need to get the days and hours in a decimal format. For example, for new DateTime(2009, 6, 19, 18, 0, 0);
I need the days as 19.75
. Day + (TimeOfDay.TotalHours / 24)
seems to work but is there a straight or better conversion? Speed is important for this calculation considering I'm also using high-resolution dates.
c# performance datetime decimal
1
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06
add a comment |
I have a DateTime
and need to get the days and hours in a decimal format. For example, for new DateTime(2009, 6, 19, 18, 0, 0);
I need the days as 19.75
. Day + (TimeOfDay.TotalHours / 24)
seems to work but is there a straight or better conversion? Speed is important for this calculation considering I'm also using high-resolution dates.
c# performance datetime decimal
I have a DateTime
and need to get the days and hours in a decimal format. For example, for new DateTime(2009, 6, 19, 18, 0, 0);
I need the days as 19.75
. Day + (TimeOfDay.TotalHours / 24)
seems to work but is there a straight or better conversion? Speed is important for this calculation considering I'm also using high-resolution dates.
c# performance datetime decimal
c# performance datetime decimal
edited Mar 28 at 0:05
BACON
9,1185 gold badges29 silver badges53 bronze badges
9,1185 gold badges29 silver badges53 bronze badges
asked Mar 27 at 22:53
rob morganrob morgan
3074 silver badges16 bronze badges
3074 silver badges16 bronze badges
1
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06
add a comment |
1
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06
1
1
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06
add a comment |
1 Answer
1
active
oldest
votes
Given...
DateTime time = new DateTime(2009, 6, 19, 18, 0, 0);
...what you have...
decimal totalDays1 = (decimal) (time.Day + time.TimeOfDay.TotalHours / 24);// 19.75M
...is already pretty terse, so I don't know how much you're wanting or expecting to improve that. You could use the TimeSpan.TotalDays
property, but it takes a bit more work to set that up...
DateTime lastDayOfPreviousMonth = new DateTime(time.Year, time.Month, 1).AddDays(-1);
decimal totalDays2 = (decimal) (time - lastDayOfPreviousMonth).TotalDays;// 19.75M
I used BenchmarkDotNet to benchmark four different methods...
using System;
using BenchmarkDotNet.Attributes;
public static class Program
static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkRunner.Run<CalculateTotalDaysBenchmarks>();
[ClrJob()]
[CoreJob()]
public class CalculateTotalDaysBenchmarks
private static readonly DateTime TestTime = new DateTime(2009, 6, 19, 18, 0, 0);
[Benchmark(Baseline = true)]
public decimal Method1_DayPlusTotalHoursDivided_CastResult()
return (decimal) (TestTime.Day + TestTime.TimeOfDay.TotalHours / 24);
[Benchmark()]
public decimal Method1_DayPlusTotalHoursDivided_CastTotalHours()
return TestTime.Day + (decimal) TestTime.TimeOfDay.TotalHours / 24;
[Benchmark()]
public decimal Method2_DayPlusTicksDivided()
return TestTime.Day + (decimal) TestTime.TimeOfDay.Ticks / TimeSpan.TicksPerDay;
[Benchmark()]
public decimal Method3_SubtractLastDayOfPreviousMonth()
DateTime lastDayOfPreviousMonth = new DateTime(TestTime.Year, TestTime.Month, 1).AddDays(-1);
return (decimal) (TestTime - lastDayOfPreviousMonth).TotalDays;
[Benchmark()]
public decimal Method4_NewTimeSpan()
return (decimal) new TimeSpan(TestTime.Day, TestTime.Hour, TestTime.Minute, TestTime.Second, TestTime.Millisecond).TotalDays;
...and got these results...
// * Summary *
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7 CPU 860 2.80GHz (Nehalem), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.505
[Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
| Method | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|------------------------------------------------ |-------- |---------:|----------:|----------:|------:|--------:|
| Method1_DayPlusTotalHoursDivided_CastResult | Clr | 118.2 ns | 1.2644 ns | 1.1827 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Clr | 263.9 ns | 0.7289 ns | 0.6462 ns | 2.23 | 0.02 |
| Method2_DayPlusTicksDivided | Clr | 194.1 ns | 0.8827 ns | 0.8256 ns | 1.64 | 0.02 |
| Method3_SubtractLastDayOfPreviousMonth | Clr | 138.9 ns | 0.4757 ns | 0.3714 ns | 1.17 | 0.01 |
| Method4_NewTimeSpan | Clr | 134.7 ns | 0.8376 ns | 0.7835 ns | 1.14 | 0.01 |
| | | | | | | |
| Method1_DayPlusTotalHoursDivided_CastResult | Core | 113.3 ns | 0.1982 ns | 0.1655 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Core | 261.3 ns | 2.9683 ns | 2.6313 ns | 2.31 | 0.02 |
| Method2_DayPlusTicksDivided | Core | 197.9 ns | 4.4254 ns | 5.2681 ns | 1.74 | 0.04 |
| Method3_SubtractLastDayOfPreviousMonth | Core | 131.1 ns | 0.8406 ns | 0.7863 ns | 1.16 | 0.01 |
| Method4_NewTimeSpan | Core | 132.1 ns | 1.1211 ns | 1.0486 ns | 1.16 | 0.01 |
What you started with is appreciably faster than the other methods.
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387696%2fhow-to-get-days-hours-minutes-seconds-from-datetime-as-a-decimal%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Given...
DateTime time = new DateTime(2009, 6, 19, 18, 0, 0);
...what you have...
decimal totalDays1 = (decimal) (time.Day + time.TimeOfDay.TotalHours / 24);// 19.75M
...is already pretty terse, so I don't know how much you're wanting or expecting to improve that. You could use the TimeSpan.TotalDays
property, but it takes a bit more work to set that up...
DateTime lastDayOfPreviousMonth = new DateTime(time.Year, time.Month, 1).AddDays(-1);
decimal totalDays2 = (decimal) (time - lastDayOfPreviousMonth).TotalDays;// 19.75M
I used BenchmarkDotNet to benchmark four different methods...
using System;
using BenchmarkDotNet.Attributes;
public static class Program
static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkRunner.Run<CalculateTotalDaysBenchmarks>();
[ClrJob()]
[CoreJob()]
public class CalculateTotalDaysBenchmarks
private static readonly DateTime TestTime = new DateTime(2009, 6, 19, 18, 0, 0);
[Benchmark(Baseline = true)]
public decimal Method1_DayPlusTotalHoursDivided_CastResult()
return (decimal) (TestTime.Day + TestTime.TimeOfDay.TotalHours / 24);
[Benchmark()]
public decimal Method1_DayPlusTotalHoursDivided_CastTotalHours()
return TestTime.Day + (decimal) TestTime.TimeOfDay.TotalHours / 24;
[Benchmark()]
public decimal Method2_DayPlusTicksDivided()
return TestTime.Day + (decimal) TestTime.TimeOfDay.Ticks / TimeSpan.TicksPerDay;
[Benchmark()]
public decimal Method3_SubtractLastDayOfPreviousMonth()
DateTime lastDayOfPreviousMonth = new DateTime(TestTime.Year, TestTime.Month, 1).AddDays(-1);
return (decimal) (TestTime - lastDayOfPreviousMonth).TotalDays;
[Benchmark()]
public decimal Method4_NewTimeSpan()
return (decimal) new TimeSpan(TestTime.Day, TestTime.Hour, TestTime.Minute, TestTime.Second, TestTime.Millisecond).TotalDays;
...and got these results...
// * Summary *
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7 CPU 860 2.80GHz (Nehalem), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.505
[Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
| Method | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|------------------------------------------------ |-------- |---------:|----------:|----------:|------:|--------:|
| Method1_DayPlusTotalHoursDivided_CastResult | Clr | 118.2 ns | 1.2644 ns | 1.1827 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Clr | 263.9 ns | 0.7289 ns | 0.6462 ns | 2.23 | 0.02 |
| Method2_DayPlusTicksDivided | Clr | 194.1 ns | 0.8827 ns | 0.8256 ns | 1.64 | 0.02 |
| Method3_SubtractLastDayOfPreviousMonth | Clr | 138.9 ns | 0.4757 ns | 0.3714 ns | 1.17 | 0.01 |
| Method4_NewTimeSpan | Clr | 134.7 ns | 0.8376 ns | 0.7835 ns | 1.14 | 0.01 |
| | | | | | | |
| Method1_DayPlusTotalHoursDivided_CastResult | Core | 113.3 ns | 0.1982 ns | 0.1655 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Core | 261.3 ns | 2.9683 ns | 2.6313 ns | 2.31 | 0.02 |
| Method2_DayPlusTicksDivided | Core | 197.9 ns | 4.4254 ns | 5.2681 ns | 1.74 | 0.04 |
| Method3_SubtractLastDayOfPreviousMonth | Core | 131.1 ns | 0.8406 ns | 0.7863 ns | 1.16 | 0.01 |
| Method4_NewTimeSpan | Core | 132.1 ns | 1.1211 ns | 1.0486 ns | 1.16 | 0.01 |
What you started with is appreciably faster than the other methods.
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
add a comment |
Given...
DateTime time = new DateTime(2009, 6, 19, 18, 0, 0);
...what you have...
decimal totalDays1 = (decimal) (time.Day + time.TimeOfDay.TotalHours / 24);// 19.75M
...is already pretty terse, so I don't know how much you're wanting or expecting to improve that. You could use the TimeSpan.TotalDays
property, but it takes a bit more work to set that up...
DateTime lastDayOfPreviousMonth = new DateTime(time.Year, time.Month, 1).AddDays(-1);
decimal totalDays2 = (decimal) (time - lastDayOfPreviousMonth).TotalDays;// 19.75M
I used BenchmarkDotNet to benchmark four different methods...
using System;
using BenchmarkDotNet.Attributes;
public static class Program
static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkRunner.Run<CalculateTotalDaysBenchmarks>();
[ClrJob()]
[CoreJob()]
public class CalculateTotalDaysBenchmarks
private static readonly DateTime TestTime = new DateTime(2009, 6, 19, 18, 0, 0);
[Benchmark(Baseline = true)]
public decimal Method1_DayPlusTotalHoursDivided_CastResult()
return (decimal) (TestTime.Day + TestTime.TimeOfDay.TotalHours / 24);
[Benchmark()]
public decimal Method1_DayPlusTotalHoursDivided_CastTotalHours()
return TestTime.Day + (decimal) TestTime.TimeOfDay.TotalHours / 24;
[Benchmark()]
public decimal Method2_DayPlusTicksDivided()
return TestTime.Day + (decimal) TestTime.TimeOfDay.Ticks / TimeSpan.TicksPerDay;
[Benchmark()]
public decimal Method3_SubtractLastDayOfPreviousMonth()
DateTime lastDayOfPreviousMonth = new DateTime(TestTime.Year, TestTime.Month, 1).AddDays(-1);
return (decimal) (TestTime - lastDayOfPreviousMonth).TotalDays;
[Benchmark()]
public decimal Method4_NewTimeSpan()
return (decimal) new TimeSpan(TestTime.Day, TestTime.Hour, TestTime.Minute, TestTime.Second, TestTime.Millisecond).TotalDays;
...and got these results...
// * Summary *
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7 CPU 860 2.80GHz (Nehalem), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.505
[Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
| Method | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|------------------------------------------------ |-------- |---------:|----------:|----------:|------:|--------:|
| Method1_DayPlusTotalHoursDivided_CastResult | Clr | 118.2 ns | 1.2644 ns | 1.1827 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Clr | 263.9 ns | 0.7289 ns | 0.6462 ns | 2.23 | 0.02 |
| Method2_DayPlusTicksDivided | Clr | 194.1 ns | 0.8827 ns | 0.8256 ns | 1.64 | 0.02 |
| Method3_SubtractLastDayOfPreviousMonth | Clr | 138.9 ns | 0.4757 ns | 0.3714 ns | 1.17 | 0.01 |
| Method4_NewTimeSpan | Clr | 134.7 ns | 0.8376 ns | 0.7835 ns | 1.14 | 0.01 |
| | | | | | | |
| Method1_DayPlusTotalHoursDivided_CastResult | Core | 113.3 ns | 0.1982 ns | 0.1655 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Core | 261.3 ns | 2.9683 ns | 2.6313 ns | 2.31 | 0.02 |
| Method2_DayPlusTicksDivided | Core | 197.9 ns | 4.4254 ns | 5.2681 ns | 1.74 | 0.04 |
| Method3_SubtractLastDayOfPreviousMonth | Core | 131.1 ns | 0.8406 ns | 0.7863 ns | 1.16 | 0.01 |
| Method4_NewTimeSpan | Core | 132.1 ns | 1.1211 ns | 1.0486 ns | 1.16 | 0.01 |
What you started with is appreciably faster than the other methods.
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
add a comment |
Given...
DateTime time = new DateTime(2009, 6, 19, 18, 0, 0);
...what you have...
decimal totalDays1 = (decimal) (time.Day + time.TimeOfDay.TotalHours / 24);// 19.75M
...is already pretty terse, so I don't know how much you're wanting or expecting to improve that. You could use the TimeSpan.TotalDays
property, but it takes a bit more work to set that up...
DateTime lastDayOfPreviousMonth = new DateTime(time.Year, time.Month, 1).AddDays(-1);
decimal totalDays2 = (decimal) (time - lastDayOfPreviousMonth).TotalDays;// 19.75M
I used BenchmarkDotNet to benchmark four different methods...
using System;
using BenchmarkDotNet.Attributes;
public static class Program
static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkRunner.Run<CalculateTotalDaysBenchmarks>();
[ClrJob()]
[CoreJob()]
public class CalculateTotalDaysBenchmarks
private static readonly DateTime TestTime = new DateTime(2009, 6, 19, 18, 0, 0);
[Benchmark(Baseline = true)]
public decimal Method1_DayPlusTotalHoursDivided_CastResult()
return (decimal) (TestTime.Day + TestTime.TimeOfDay.TotalHours / 24);
[Benchmark()]
public decimal Method1_DayPlusTotalHoursDivided_CastTotalHours()
return TestTime.Day + (decimal) TestTime.TimeOfDay.TotalHours / 24;
[Benchmark()]
public decimal Method2_DayPlusTicksDivided()
return TestTime.Day + (decimal) TestTime.TimeOfDay.Ticks / TimeSpan.TicksPerDay;
[Benchmark()]
public decimal Method3_SubtractLastDayOfPreviousMonth()
DateTime lastDayOfPreviousMonth = new DateTime(TestTime.Year, TestTime.Month, 1).AddDays(-1);
return (decimal) (TestTime - lastDayOfPreviousMonth).TotalDays;
[Benchmark()]
public decimal Method4_NewTimeSpan()
return (decimal) new TimeSpan(TestTime.Day, TestTime.Hour, TestTime.Minute, TestTime.Second, TestTime.Millisecond).TotalDays;
...and got these results...
// * Summary *
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7 CPU 860 2.80GHz (Nehalem), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.505
[Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
| Method | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|------------------------------------------------ |-------- |---------:|----------:|----------:|------:|--------:|
| Method1_DayPlusTotalHoursDivided_CastResult | Clr | 118.2 ns | 1.2644 ns | 1.1827 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Clr | 263.9 ns | 0.7289 ns | 0.6462 ns | 2.23 | 0.02 |
| Method2_DayPlusTicksDivided | Clr | 194.1 ns | 0.8827 ns | 0.8256 ns | 1.64 | 0.02 |
| Method3_SubtractLastDayOfPreviousMonth | Clr | 138.9 ns | 0.4757 ns | 0.3714 ns | 1.17 | 0.01 |
| Method4_NewTimeSpan | Clr | 134.7 ns | 0.8376 ns | 0.7835 ns | 1.14 | 0.01 |
| | | | | | | |
| Method1_DayPlusTotalHoursDivided_CastResult | Core | 113.3 ns | 0.1982 ns | 0.1655 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Core | 261.3 ns | 2.9683 ns | 2.6313 ns | 2.31 | 0.02 |
| Method2_DayPlusTicksDivided | Core | 197.9 ns | 4.4254 ns | 5.2681 ns | 1.74 | 0.04 |
| Method3_SubtractLastDayOfPreviousMonth | Core | 131.1 ns | 0.8406 ns | 0.7863 ns | 1.16 | 0.01 |
| Method4_NewTimeSpan | Core | 132.1 ns | 1.1211 ns | 1.0486 ns | 1.16 | 0.01 |
What you started with is appreciably faster than the other methods.
Given...
DateTime time = new DateTime(2009, 6, 19, 18, 0, 0);
...what you have...
decimal totalDays1 = (decimal) (time.Day + time.TimeOfDay.TotalHours / 24);// 19.75M
...is already pretty terse, so I don't know how much you're wanting or expecting to improve that. You could use the TimeSpan.TotalDays
property, but it takes a bit more work to set that up...
DateTime lastDayOfPreviousMonth = new DateTime(time.Year, time.Month, 1).AddDays(-1);
decimal totalDays2 = (decimal) (time - lastDayOfPreviousMonth).TotalDays;// 19.75M
I used BenchmarkDotNet to benchmark four different methods...
using System;
using BenchmarkDotNet.Attributes;
public static class Program
static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkRunner.Run<CalculateTotalDaysBenchmarks>();
[ClrJob()]
[CoreJob()]
public class CalculateTotalDaysBenchmarks
private static readonly DateTime TestTime = new DateTime(2009, 6, 19, 18, 0, 0);
[Benchmark(Baseline = true)]
public decimal Method1_DayPlusTotalHoursDivided_CastResult()
return (decimal) (TestTime.Day + TestTime.TimeOfDay.TotalHours / 24);
[Benchmark()]
public decimal Method1_DayPlusTotalHoursDivided_CastTotalHours()
return TestTime.Day + (decimal) TestTime.TimeOfDay.TotalHours / 24;
[Benchmark()]
public decimal Method2_DayPlusTicksDivided()
return TestTime.Day + (decimal) TestTime.TimeOfDay.Ticks / TimeSpan.TicksPerDay;
[Benchmark()]
public decimal Method3_SubtractLastDayOfPreviousMonth()
DateTime lastDayOfPreviousMonth = new DateTime(TestTime.Year, TestTime.Month, 1).AddDays(-1);
return (decimal) (TestTime - lastDayOfPreviousMonth).TotalDays;
[Benchmark()]
public decimal Method4_NewTimeSpan()
return (decimal) new TimeSpan(TestTime.Day, TestTime.Hour, TestTime.Minute, TestTime.Second, TestTime.Millisecond).TotalDays;
...and got these results...
// * Summary *
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7 CPU 860 2.80GHz (Nehalem), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.505
[Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
| Method | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|------------------------------------------------ |-------- |---------:|----------:|----------:|------:|--------:|
| Method1_DayPlusTotalHoursDivided_CastResult | Clr | 118.2 ns | 1.2644 ns | 1.1827 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Clr | 263.9 ns | 0.7289 ns | 0.6462 ns | 2.23 | 0.02 |
| Method2_DayPlusTicksDivided | Clr | 194.1 ns | 0.8827 ns | 0.8256 ns | 1.64 | 0.02 |
| Method3_SubtractLastDayOfPreviousMonth | Clr | 138.9 ns | 0.4757 ns | 0.3714 ns | 1.17 | 0.01 |
| Method4_NewTimeSpan | Clr | 134.7 ns | 0.8376 ns | 0.7835 ns | 1.14 | 0.01 |
| | | | | | | |
| Method1_DayPlusTotalHoursDivided_CastResult | Core | 113.3 ns | 0.1982 ns | 0.1655 ns | 1.00 | 0.00 |
| Method1_DayPlusTotalHoursDivided_CastTotalHours | Core | 261.3 ns | 2.9683 ns | 2.6313 ns | 2.31 | 0.02 |
| Method2_DayPlusTicksDivided | Core | 197.9 ns | 4.4254 ns | 5.2681 ns | 1.74 | 0.04 |
| Method3_SubtractLastDayOfPreviousMonth | Core | 131.1 ns | 0.8406 ns | 0.7863 ns | 1.16 | 0.01 |
| Method4_NewTimeSpan | Core | 132.1 ns | 1.1211 ns | 1.0486 ns | 1.16 | 0.01 |
What you started with is appreciably faster than the other methods.
edited Mar 27 at 23:56
answered Mar 27 at 23:07
BACONBACON
9,1185 gold badges29 silver badges53 bronze badges
9,1185 gold badges29 silver badges53 bronze badges
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
add a comment |
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
Not sure if one is better than the other when it comes to speed.... new TimeSpan(cd.Day, cd.Hour, cd.Minute, cd.Second, cd.Millisecond).TotalDays;
– rob morgan
Mar 27 at 23:11
1
1
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Ah, that works, too, though it truncates any sub-millisecond time, if that matters to you. Is speed what you're going for? Clarity? Less characters?
– BACON
Mar 27 at 23:13
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
Speed is important for this calculation, consider I'm using also using hi-res dates.
– rob morgan
Mar 27 at 23:14
1
1
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
I have added benchmark code and results to my answer.
– BACON
Mar 27 at 23:58
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387696%2fhow-to-get-days-hours-minutes-seconds-from-datetime-as-a-decimal%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Have you tried using a TimeSpan?
– Pedro Rodrigues
Mar 27 at 23:00
I think new timespan().totaldays works
– rob morgan
Mar 27 at 23:06