How to parse string like 30:15 to TimeSpan in C#? 30:15 means 30 hours and 15 minutes.
string span = "30:15";
TimeSpan ts = TimeSpan.FromHours(
Convert.ToDouble(span.Split(':')[0])).
Add(TimeSpan.FromMinutes(
Convert.ToDouble((span.Split(':')[1]))));
This does not seem too elegant.
If you're certain that the format will always be "HH:mm" then try something like this:
string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]), // hours
int.Parse(span.Split(':')[1]), // minutes
0); // seconds
Similar to Luke's answer:
String span = "123:45";
Int32 colon = span.IndexOf(':');
TimeSpan timeSpan = new TimeSpan(Int32.Parse(span.Substring(0, colon - 1)),
Int32.Parse(span.Substring(colon + 1)), 0);
Obviously it assumes the original string is well-formed (composed of two parts separated by colon and parsable to an integer number).
I'm using a simple method that I devised a long time ago and just posted today to my blog:
public static class TimeSpanExtensions
{
static int[] weights = { 60 * 60 * 1000, 60 * 1000, 1000, 1 };
public static TimeSpan ToTimeSpan(this string s)
{
string[] parts = s.Split('.', ':');
long ms = 0;
for (int i = 0; i < parts.Length && i < weights.Length; i++)
ms += Convert.ToInt64(parts[i]) * weights[i];
return TimeSpan.FromMilliseconds(ms);
}
}
This can handle a lot more situations than the simpler solutions provided before, but has its own shortcomings. I discuss it further here.
Now, if you're in .NET 4 you can shorten the ToTimeSpan implementation to:
public static TimeSpan ToTimeSpan(this string s)
{
return TimeSpan.FromMilliseconds(s.Split('.', ':')
.Zip(weights, (d, w) => Convert.ToInt64(d) * w).Sum());
}
You can even make it an one-liner if you don't mind using horizontal screen state...
Similar to Lukes answer, with a lot more code and room for improvement. BUT it deals with negatives Hours ("-30:15") aswell, so maybe it can help someone.
public static double GetTotalHours(String s)
{
bool isNegative = false;
if (s.StartsWith("-"))
isNegative = true;
String[] splitted = s.Split(':');
int hours = GetNumbersAsInt(splitted[0]);
int minutes = GetNumbersAsInt(splitted[1]);
if (isNegative)
{
hours = hours * (-1);
minutes = minutes * (-1);
}
TimeSpan t = new TimeSpan(hours, minutes, 0);
return t.TotalHours;
}
public static int GetNumbersAsInt(String input)
{
String output = String.Empty;
Char[] chars = input.ToCharArray(0, input.Length);
for (int i = 0; i < chars.Length; i++)
{
if (Char.IsNumber(chars[i]) == true)
output = output + chars[i];
}
return int.Parse(output);
}
usage
double result = GetTotalHours("30:15");
double result2 = GetTotalHours("-30:15");
Normally one would use TimeSpan.ParseExact where a specific format is required. But the only hours formats that can be specified are as parts of days (see Custom TimeSpan Format Strings).
Therefore you will need to do the work yourself:
string input = "30:24";
var parts = input.Split(':');
var hours = Int32.Parse(parts[0]);
var minutes = Int32.Parse(parts[1]);
var result = new TimeSpan(hours, minutes, 0);
(But with some error checking.)
The three integer constructor of timespan allows hours >= 24 overflowing into the days count.
Based on Jan's Answer
.NET 5
/// <summary>
/// 1 number : hours "0" to "0:0:0" , "-1" to "-01:00:00"
/// 2 numbers : hours, minutes "1:2" to "01:02:00"
/// 3 numbers : hours, minutes, seconds "1:2:3" to "01:02:03"
/// 4 numbers : days, hours, minutes, seconds "1:2:3:4" to "1.02:03:04"
/// Any char can be used as separator. "1,2 3aaaa4" to "1.02:03:04"
/// </summary>
/// <param name="timeSpanString"></param>
/// <param name="ts"></param>
/// <returns>true : conversion succeeded</returns>
public static bool GetTimeSpan(string timeSpanString, ref TimeSpan ts)
{
bool isNegative = timeSpanString.StartsWith("-"); // "-1:2:3" is true
var digitsString = Regex.Replace(timeSpanString, "[^0-9]", " "); // "-1:2:3" to " 1 2 3"
var s = digitsString.Split(' ', StringSplitOptions.RemoveEmptyEntries); // "1","2","3"
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
switch (s.Length)
{
case 1:
hours = int.Parse(s[0]);
break;
case 2:
hours = int.Parse(s[0]);
minutes = int.Parse(s[1]);
break;
case 3:
hours = int.Parse(s[0]);
minutes = int.Parse(s[1]);
seconds = int.Parse(s[2]);
break;
case 4:
days = int.Parse(s[0]);
hours = int.Parse(s[1]);
minutes = int.Parse(s[2]);
seconds = int.Parse(s[3]);
break;
default:
return false; //no digits or length > 4
}
if (isNegative)
{
ts = new TimeSpan(-days, -hours, -minutes, -seconds);
}
else
{
ts = new TimeSpan(days, hours, minutes, seconds);
}
return true;
}
TimeSpanHelper
Convert TimeSpan to over 24 hours number. TimeSpan Converter, Rule for TextBox.
Related
Im trying to convert a decmial number of hours to days, hours and minutes.
This is what I have so far, its not quite there yet. I need to subtract the number of hours from the days from the hours part if that makes sense?
/// <summary>
/// Converts from a decimal value to DD:HH:MM
/// </summary>
/// <param name="dHours">The total number of hours</param>
/// <returns>DD:HH:MM string</returns>
public static string ConvertFromDecimalToDDHHMM(decimal dHours)
{
try
{
decimal hours = Math.Floor(dHours); //take integral part
decimal minutes = (dHours - hours) * 60.0M; //multiply fractional part with 60
int D = (int)Math.Floor(dHours / 24);
int H = (int)Math.Floor(hours);
int M = (int)Math.Floor(minutes);
//int S = (int)Math.Floor(seconds); //add if you want seconds
string timeFormat = String.Format("{0:00}:{1:00}:{2:00}", D, H, M);
return timeFormat;
}
catch (Exception)
{
throw;
}
}
SOLUTION:
/// <summary>
/// Converts from a decimal value to DD:HH:MM
/// </summary>
/// <param name="dHours">The total number of hours</param>
/// <returns>DD:HH:MM string</returns>
public static string ConvertFromDecimalToDDHHMM(decimal dHours)
{
try
{
decimal hours = Math.Floor(dHours); //take integral part
decimal minutes = (dHours - hours) * 60.0M; //multiply fractional part with 60
int D = (int)Math.Floor(dHours / 24);
int H = (int)Math.Floor(hours - (D * 24));
int M = (int)Math.Floor(minutes);
//int S = (int)Math.Floor(seconds); //add if you want seconds
string timeFormat = String.Format("{0:00}:{1:00}:{2:00}", D, H, M);
return timeFormat;
}
catch (Exception)
{
throw;
}
}
You could use TimeSpan.FromHours to get the timespan, then you have all you need:
TimeSpan ts = TimeSpan.FromHours(Decimal.ToDouble(dHours));
For example:
int D = ts.Days;
int H = ts.Hours;
int M = ts.Minutes;
You need to subtract (D * 24) from hours... or you could just use:
int H = ((int) dHours) % 24;
If you're going to cast to int anyway, there's no need to call Math.Floor. So for example, you could actually use:
// I'd rename dHours as well, by the way...
int wholeHours = (int) dHours;
int days = wholeHours / 24;
int hours = wholeHours % 24;
int minutse = (int) ((dHours % 1M) * 60);
On the other hand, you need to be careful if it can be negative - all kinds of things could end up screwy in that case. If you don't believe you have to handle that, I'd explicitly check it and throw an exception if dHours is negative before you do anything else.
(Note that your try/catch block is pointless and distracting at the moment. Just get rid of it.)
Why not do something like this?
double d = 25.23523;
Timespan t = TimeSpan.FromHours(d);
This will give you:
t = 1.01:14:06.8280000
Then you can interrogate the TimeSpan object as you wish: http://msdn.microsoft.com/en-us/library/system.timespan.aspx
NOTE: TimeSpan.FromHours needs a double input, not a decimal.
Simple.
double counter = 0.25;
TimeSpan span = TimeSpan.FromMinutes(counter);
textbox1.Text = span.ToString(#"hh\:mm\:ss");
result will be 00:00:15 seconds. If counter = 1, then the result will be 00:01:00 and so on.
here is another post which expains it pretty good.
Convert date to string format yyyy-mm-dd HH:MM:SS - C#
MyDateTime.ToString("yyyy-MM-dd hh:mm:ss");
also
http://blog.stevex.net/string-formatting-in-csharp/
public static string GetTimeString(Decimal dHours)
{
DateTime dTime = new DateTime().AddHours(dHours);
return dTime.ToString("HH:mm:ss"); // HH: 24h or hh: 12h
}
I would like to calculate the remaining minutes to the "next" half an hour or hour.
Say i get a start time string of 07:15, i want it to calculate the remaining minutes to the nearest half an hour (07:30).
That would be 15min.
Then i can also have an instance where the start time can be 07:45 and i want it to calculate the remaining minutes to the nearest hour (08:00).
That would also be 15min.
So any string less then 30min in a hour would calculate to the nearest half an hour (..:30) and any string over 30min would calculate to the nearest hour (..:00).
I don't want to do a bunch of if statements, because i get from time strings that can start from and minute in an hour.
This is what i do not want to do:
if (int.Parse(fromTimeString.Right(2)) < 30)
{
//Do Calculation
}
else
{
//Do Calculation
}
public static string Right(this String stringValue, int noOfCharacters)
{
string result = null;
if (stringValue.Length >= noOfCharacters)
{
result = stringValue.Substring(stringValue.Length - noOfCharacters, noOfCharacters);
}
else
{
result = "";
}
return result;
}
Is there not an easier way with linq or with the DateTime class
Use modulo operator % with 30. Your result will be equal to (60 - currentMinutes) % 30. About LINQ its used for collections so i can't realy see how it can be used in your case.
You can use this DateTime tick-round approach to get the timespan until next half hour:
var minutes = 30;
var now = DateTime.Now;
var ticksMin = TimeSpan.FromMinutes(minutes).Ticks;
DateTime rounded = new DateTime(((now.Ticks + (ticksMin/2)) / ticksMin) * ticksMin);
var diff=rounded-now;
var minUntilNext = diff.TotalMinutes > 0 ? diff.TotalMinutes : minutes + diff.TotalMinutes;
var minutesToNextHalfHour = (60 - yourDateTimeVariable.Minutes) % 30;
This should do it:
int remainingMinutes = (current.Minute >= 30)
? 60 - current.Minute
: 30 - current.Minute;
var hhmm = fromTimeString.Split(':');
var mins = int.Parse(hhmm[1]);
var remainingMins = (60 - mins) % 30;
var str = "7:16";
var datetime = DateTime.ParseExact(str, "h:mm", new CultureInfo("en-US"));
var minutesPastHalfHour = datetime.Minute % 30;
var minutesBeforeHalfHour = 30 - minutesPastHalfHour;
I would use modulo + TimeSpan.TryParse:
public static int ComputeTime(string time)
{
TimeSpan ts;
if (TimeSpan.TryParse(time, out ts))
{
return (60 - ts.Minutes) % 30;
}
throw new ArgumentException("Time is not valid", "time");
}
private static void Main(string[] args)
{
string test1 = "7:27";
string test2 = "7:42";
Console.WriteLine(ComputeTime(test1));
Console.WriteLine(ComputeTime(test2));
Console.ReadLine();
}
i have:
jobElement.CreationDate = jobElement.CreationDate + TimeSpan.FromHours(24.0);
i would like to have not strictly 24 hours, but with +- 10 seconds Buffer. like 23.59.10 and 00.00.10
hot to reach that with c#?
This will generate CreationDate + 23:50 and CreationDate + 24:10 with equal probability:
Random random = new Random();
TimeSpan buffer = TimeSpan.FromSeconds(10);
TimeSpan span = TimeSpan.FromHours(24.0);
// 50% of the time do this
if(random.Next() % 2 == 0)
{
span += buffer;
}
// The rest of the time do this
else
{
span -= buffer;
}
jobElement.CreationDate = jobElement.CreationDate + span;
What do you need to do with that?
If you need to any comparison create custom class with overwritten equality operators.
I'm not 100% sure what you want here but I'll give it a shot
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1).AddSeconds(8);
These two are now 24 hours and 8 seconds apart.
Then if you want to see if they are "almost" 24 hour appart, you can do something like this:
if( Math.Abs((dt1-dt2.AddDays(-1))) < 10 ){
//dt2 is 24 after dt1 +- 10 seconds
}else{
//they are not
}
First time (00.00.00) of current date -/+ 10 secs would be:
DateTime dateFrom = jobElement.CreationDate.Date.AddSeconds(-10);
DateTime dateTo = jobElement.CreationDate.Date.AddSeconds(10);
Is that it?
I'll add this variant. It's different from others because it isn't "second based" but "tick" based (the tick is the smallest time that a TimeSpan/DateTime can compute)
const int sec = 10; // +/- seconds of the "buffer"
const int ticksSec = 10000000; // There are 10000000 Ticks in a second
Random r = new Random();
int rng = r.Next(-sec * ticksSec, sec * ticksSec + 1); // r.Next is upper-bound exclusive
var ts = TimeSpan.FromHours(24) + TimeSpan.FromTicks(rng);
jobElement.CreationDate = jobElement.CreationDate + ts;
There are limits in the Random class (it can't generate a long, and generating a "constrained" long (a long with maxValue = x) is non-trivial based only on the Random class, so this will work for up to 3 minutes and something of "buffer" (214 seconds to be more exact).
If you want +/- 10 with all numbers between
Random r = new Random();
int x = r.Next(-10, 11);
var ts = TimeSpan.FromHours(24).Add(TimeSpan.FromSeconds((double)x));
jobElement.CreationDate = jobElement.CreationDate + ts;
How to parse string like 30:15 to TimeSpan in C#? 30:15 means 30 hours and 15 minutes.
string span = "30:15";
TimeSpan ts = TimeSpan.FromHours(
Convert.ToDouble(span.Split(':')[0])).
Add(TimeSpan.FromMinutes(
Convert.ToDouble((span.Split(':')[1]))));
This does not seem too elegant.
If you're certain that the format will always be "HH:mm" then try something like this:
string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]), // hours
int.Parse(span.Split(':')[1]), // minutes
0); // seconds
Similar to Luke's answer:
String span = "123:45";
Int32 colon = span.IndexOf(':');
TimeSpan timeSpan = new TimeSpan(Int32.Parse(span.Substring(0, colon - 1)),
Int32.Parse(span.Substring(colon + 1)), 0);
Obviously it assumes the original string is well-formed (composed of two parts separated by colon and parsable to an integer number).
I'm using a simple method that I devised a long time ago and just posted today to my blog:
public static class TimeSpanExtensions
{
static int[] weights = { 60 * 60 * 1000, 60 * 1000, 1000, 1 };
public static TimeSpan ToTimeSpan(this string s)
{
string[] parts = s.Split('.', ':');
long ms = 0;
for (int i = 0; i < parts.Length && i < weights.Length; i++)
ms += Convert.ToInt64(parts[i]) * weights[i];
return TimeSpan.FromMilliseconds(ms);
}
}
This can handle a lot more situations than the simpler solutions provided before, but has its own shortcomings. I discuss it further here.
Now, if you're in .NET 4 you can shorten the ToTimeSpan implementation to:
public static TimeSpan ToTimeSpan(this string s)
{
return TimeSpan.FromMilliseconds(s.Split('.', ':')
.Zip(weights, (d, w) => Convert.ToInt64(d) * w).Sum());
}
You can even make it an one-liner if you don't mind using horizontal screen state...
Similar to Lukes answer, with a lot more code and room for improvement. BUT it deals with negatives Hours ("-30:15") aswell, so maybe it can help someone.
public static double GetTotalHours(String s)
{
bool isNegative = false;
if (s.StartsWith("-"))
isNegative = true;
String[] splitted = s.Split(':');
int hours = GetNumbersAsInt(splitted[0]);
int minutes = GetNumbersAsInt(splitted[1]);
if (isNegative)
{
hours = hours * (-1);
minutes = minutes * (-1);
}
TimeSpan t = new TimeSpan(hours, minutes, 0);
return t.TotalHours;
}
public static int GetNumbersAsInt(String input)
{
String output = String.Empty;
Char[] chars = input.ToCharArray(0, input.Length);
for (int i = 0; i < chars.Length; i++)
{
if (Char.IsNumber(chars[i]) == true)
output = output + chars[i];
}
return int.Parse(output);
}
usage
double result = GetTotalHours("30:15");
double result2 = GetTotalHours("-30:15");
Normally one would use TimeSpan.ParseExact where a specific format is required. But the only hours formats that can be specified are as parts of days (see Custom TimeSpan Format Strings).
Therefore you will need to do the work yourself:
string input = "30:24";
var parts = input.Split(':');
var hours = Int32.Parse(parts[0]);
var minutes = Int32.Parse(parts[1]);
var result = new TimeSpan(hours, minutes, 0);
(But with some error checking.)
The three integer constructor of timespan allows hours >= 24 overflowing into the days count.
Based on Jan's Answer
.NET 5
/// <summary>
/// 1 number : hours "0" to "0:0:0" , "-1" to "-01:00:00"
/// 2 numbers : hours, minutes "1:2" to "01:02:00"
/// 3 numbers : hours, minutes, seconds "1:2:3" to "01:02:03"
/// 4 numbers : days, hours, minutes, seconds "1:2:3:4" to "1.02:03:04"
/// Any char can be used as separator. "1,2 3aaaa4" to "1.02:03:04"
/// </summary>
/// <param name="timeSpanString"></param>
/// <param name="ts"></param>
/// <returns>true : conversion succeeded</returns>
public static bool GetTimeSpan(string timeSpanString, ref TimeSpan ts)
{
bool isNegative = timeSpanString.StartsWith("-"); // "-1:2:3" is true
var digitsString = Regex.Replace(timeSpanString, "[^0-9]", " "); // "-1:2:3" to " 1 2 3"
var s = digitsString.Split(' ', StringSplitOptions.RemoveEmptyEntries); // "1","2","3"
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
switch (s.Length)
{
case 1:
hours = int.Parse(s[0]);
break;
case 2:
hours = int.Parse(s[0]);
minutes = int.Parse(s[1]);
break;
case 3:
hours = int.Parse(s[0]);
minutes = int.Parse(s[1]);
seconds = int.Parse(s[2]);
break;
case 4:
days = int.Parse(s[0]);
hours = int.Parse(s[1]);
minutes = int.Parse(s[2]);
seconds = int.Parse(s[3]);
break;
default:
return false; //no digits or length > 4
}
if (isNegative)
{
ts = new TimeSpan(-days, -hours, -minutes, -seconds);
}
else
{
ts = new TimeSpan(days, hours, minutes, seconds);
}
return true;
}
TimeSpanHelper
Convert TimeSpan to over 24 hours number. TimeSpan Converter, Rule for TextBox.
How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
Let's say I have 80 seconds; are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like Convert.ToDateTime or something?
For .Net <= 4.0 Use the TimeSpan class.
TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(#"hh\:mm\:ss\:fff");
(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds to avoid an exception.
For .NET > 4.0 you can use
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(#"hh\:mm\:ss\:fff");
or if you want date time format then you can also do this
TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = dateTime.ToString("hh:mm:tt");
For more you can check Custom TimeSpan Format Strings
If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:
TimeSpan ts = TimeSpan.FromSeconds(80);
You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.
I did some benchmarks to see what's the fastest way and these are my results and conclusions. I ran each method 10M times and added a comment with the average time per run.
If your input milliseconds are not limited to one day (your result may be 143:59:59.999), these are the options, from faster to slower:
// 0.86 ms
static string Method1(int millisecs)
{
int hours = millisecs / 3600000;
int mins = (millisecs % 3600000) / 60000;
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}", hours, mins, millisecs % 60000 / 1000, millisecs % 1000);
}
// 0.89 ms
static string Method2(int millisecs)
{
double s = millisecs % 60000 / 1000.0;
millisecs /= 60000;
int mins = millisecs % 60;
int hours = millisecs / 60;
return string.Format("{0:D2}:{1:D2}:{2:00.000}", hours, mins, s);
}
// 0.95 ms
static string Method3(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
(int)t.TotalHours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
If your input milliseconds are limited to one day (your result will never be greater then 23:59:59.999), these are the options, from faster to slower:
// 0.58 ms
static string Method5(int millisecs)
{
// Fastest way to create a DateTime at midnight
// Make sure you use the appropriate decimal separator
return DateTime.FromBinary(599266080000000000).AddMilliseconds(millisecs).ToString("HH:mm:ss.fff");
}
// 0.59 ms
static string Method4(int millisecs)
{
// Make sure you use the appropriate decimal separator
return TimeSpan.FromMilliseconds(millisecs).ToString(#"hh\:mm\:ss\.fff");
}
// 0.93 ms
static string Method6(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
In case your input is just seconds, the methods are slightly faster. Again, if your input seconds are not limited to one day (your result may be 143:59:59):
// 0.63 ms
static string Method1(int secs)
{
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
secs = secs % 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}
// 0.64 ms
static string Method2(int secs)
{
int s = secs % 60;
secs /= 60;
int mins = secs % 60;
int hours = secs / 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, s);
}
// 0.70 ms
static string Method3(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
(int)t.TotalHours,
t.Minutes,
t.Seconds);
}
And if your input seconds are limited to one day (your result will never be greater then 23:59:59):
// 0.33 ms
static string Method5(int secs)
{
// Fastest way to create a DateTime at midnight
return DateTime.FromBinary(599266080000000000).AddSeconds(secs).ToString("HH:mm:ss");
}
// 0.34 ms
static string Method4(int secs)
{
return TimeSpan.FromSeconds(secs).ToString(#"hh\:mm\:ss");
}
// 0.70 ms
static string Method6(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
}
As a final comment, let me add that I noticed that string.Format is a bit faster if you use D2 instead of 00.
TimeSpan.FromSeconds(80);
http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
I'd suggest you use the TimeSpan class for this.
public static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(80);
Console.WriteLine(t.ToString());
t = TimeSpan.FromSeconds(868693412);
Console.WriteLine(t.ToString());
}
Outputs:
00:01:20
10054.07:43:32
In VB.NET, but it's the same in C#:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
For .NET < 4.0 (e.x: Unity) you can write an extension method to have the TimeSpan.ToString(string format) behavior like .NET > 4.0
public static class TimeSpanExtensions
{
public static string ToString(this TimeSpan time, string format)
{
DateTime dateTime = DateTime.Today.Add(time);
return dateTime.ToString(format);
}
}
And from anywhere in your code you can use it like:
var time = TimeSpan.FromSeconds(timeElapsed);
string formattedDate = time.ToString("hh:mm:ss:fff");
This way you can format any TimeSpanobject by simply calling ToString from anywhere of your code.
Why do people need TimeSpan AND DateTime if we have DateTime.AddSeconds()?
var dt = new DateTime(2015, 1, 1).AddSeconds(totalSeconds);
The date is arbitrary.
totalSeconds can be greater than 59 and it is a double.
Then you can format your time as you want using DateTime.ToString():
dt.ToString("H:mm:ss");
This does not work if totalSeconds < 0 or > 59:
new DateTime(2015, 1, 1, 0, 0, totalSeconds)
to get total seconds
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
and to get datetime from seconds
var thatDateTime = new DateTime().AddSeconds(i)
This will return in hh:mm:ss format
public static string ConvertTime(long secs)
{
TimeSpan ts = TimeSpan.FromSeconds(secs);
string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
return displayTime;
}
TimeSpan t = TimeSpan.FromSeconds(EnergyRestoreTimer.Instance.SecondsForRestore);
string sTime = EnergyRestoreTimer.Instance.SecondsForRestore < 3600
? $"{t.Hours:D2}:{t.Minutes:D2}:{t.Seconds:D2}"
: $"{t.Minutes:D2}:{t.Seconds:D2}";
time.text = sTime;
private string ConvertTime(double miliSeconds)
{
var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
// Converts the total miliseconds to the human readable time format
return timeSpan.ToString(#"hh\:mm\:ss\:fff");
}
//Test
[TestCase(1002, "00:00:01:002")]
[TestCase(700011, "00:11:40:011")]
[TestCase(113879834, "07:37:59:834")]
public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
{
// Arrange
var obj = new Class();;
// Act
var resultMessage = obj.ConvertTime(totalMiliSeconds);
// Assert
Assert.AreEqual(expectedMessage, resultMessage);
}