Convert TimeSpan from format "hh:mm:ss" to "hh:mm" - c#

I want to show in a TextBox only hour and minutes
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
how to show only hours and minutes "hh.mm"

You need to convert your data to TimeSpan and then use format:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(#"hh\:mm"));
In your case:
var test = dataRow.Field<TimeSpan>("fstart").ToString(#"hh\:mm"));
Remember to escape the colon :
You may see: Custom TimeSpan Format Strings

There is no need to convert from hh.mm.ss to hh.mm. TimeSpan is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the TimeSpan into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case hh.mm.ss.
string formatted = timespan.ToString(#"hh\.mm");
Note: This overload of ToString exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.
The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format(#"{0:hh\.mm}", timespan); // ==> 00:20:34
However, you can construct the string like this
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
or starting with VS2015 / C# 6.0, using string interpolation:
string formatted = $#"{timespan:hh\:mm}";

You can use TimeSpan methods:
ToString("hh':'mm")
// or
ToString(#"hh\:mm")
Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;

I know this is a very old question. If anyone wants to show single-digit hours when your hours are a single digit then you can use
var hoursWithMinutes = TimeSpan.FromHours(hours).ToString(#"h\:mm")
This way, when your hours are double-digit I mean greater than 9 then it will be showing 10:00 something like that.

The previous solutions don't run if hours>24, try this solution if you have time in minutes very big
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;

You can achieve this by:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(#"hh\:mm")

Related

C# seconds in string format to TimeSpan

I'm having a bit of a issue with this.
What I want to do is take this string 27.0 and convert it to a timespan.
I tried every way I could think of in order to get it to work.
TimeSpan.Parse("27.0") I know it's a format issue but I'm not sure of the format to use.
I basically have 4 values
27.0
52.4
1:24.4
1:43.3
Is there a easy way to handle all these formats?
Thanks!
Sorry these are all seconds except the 1 is minute so 1 minute 24 seconds 4 milliseconds
You can use two different approaches. Use one of the TimeSpan.From...() methods. Those convert numbers to a TimeSpan. For example to convert the double 27 to a TimeSpan with 27 seconds you use
var ts = TimeSpan.FromSeconds(27)
The only problem you will face here is that it does not allow you to specify a string. So you could for example first parse your string as an double. If you do it naivly just like that, it can be you get what you wanted, or not.
var ts = TimeSpan.FromSeconds(double.Parse("27.0"))
But if you run this for example on a system with a German locale you will get a TimeSpan with 4 minutes and 30 seconds. The reason for that is that a dot in German is not a divider for a number, it is the thousand seperator. So that number is parsed as "270". So to be safe you should also provide a NumberFormat. A better way would be.
var culture = new CultureInfo("en-US");
var tsc = TimeSpan.FromSeconds(double.Parse("27.0", culture.NumberFormat));
Now you get your 27 seconds. But the problem is still that it only parses your two first strings correctly. Your other 3 strings will still not parse, because you can't convert them to numbers. But I still added this, to be aware of culture difference if you just go up and try to parse a number to an double und use TimeSpan.FromSeconds() and so on.
Now lets look further how you can parse every string. There exists TimeSpan.Parse() and TimeSpan.ParseExact().
Now you still must knew that TimeSpan.Parse() uses culture specific formatting. In a country where a time is not separated with colons a TimeSpan.Parse() will fail. On Top of that, TimeSpan assumes a format "hh:mm" at minimum. But the Colon in this format is culture-sensitive. You could use the "en-US" Culture once again, but it wouldn't solve the problem because he doesn't accept the format "27.0".
That is the reason why you must use the TimeSpan.ParseExact() method and and provide the formats that this method should be able to parse. It also allows you to specify formats that he should be able to parse. You now should end with something like this.
var culture = new CultureInfo("en-US");
var formats = new string[] {
#"s\.f",
#"ss\.f",
#"ss\.ff",
#"m\:ss\.f",
#"m\:ss\.ff",
#"mm\:ss\.ff"
};
foreach ( var str in new string[] { "27.0", "52.4", "1:24.4", "1:43.3" } ) {
var ts = TimeSpan.ParseExact(str, formats, culture.NumberFormat);
Console.WriteLine(ts.ToString());
}
Note that in this example I added a backslash to escape the dot and the colon. If you don't do this then the formatter itself treats this as a culture-sensitive separator. But what you want is exactly the colon or the dot.
The output of this code will be
00:00:27
00:00:52.4000000
00:01:24.4000000
00:01:43.3000000
try something like this:
var timeString = "1:24.4";
var timeComponents = timeString.Split(':', '.').Reverse().ToList();
var milliseconds = timeComponents.Any() ? int.Parse(timeComponents[0]) : 0;
var seconds = timeComponents.Count() > 1 ? int.Parse(timeComponents[1]) : 0;
var minutes = timeComponents.Count() > 2 ? int.Parse(timeComponents[2]) : 0;
var timeSpan = new TimeSpan(0, 0, minutes, seconds, milliseconds);
this will deal with the milliseconds literally. You may want to pad the string component of the milliseconds with '0's, as pointed out in the comments.

How to convert date to 'ccyymmddhhmmss' format?

How to convert date to 'ccyymmddhhmmss' format in c#?
You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));
From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.
#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

I want to split my minutes, seconds and hundreds to seconds and hundreds

I want to set a time in minutes to only seconds, does anyone know what's wrong with this code? (time mm:ss,hh to ss,hh. Example 01:12,10 to 72,10 seconds)
public double timeToSeconds(string TimeToSplit)
{
string[] Timesplitter = new string[2];
double minutes;
double seconds;
Timesplitter = TimeToSplit.Split(':');
minutes = double.Parse(Timesplitter[0]); //double with minutes
seconds = double.Parse(Timesplitter[1]); //double with seconds
if (minutes != 0)
{
seconds = seconds + (minutes * 60);
}
return seconds;
}
You should use a TimeSpan. Here's one way to parse that:
TimeSpan ts = TimeSpan.ParseExact("01:12,10", "mm\\:ss\\,ff", null);
double seconds = ts.TotalSeconds;
return seconds; // it's 72.1
You are better working with the DateTime object rather than doubles and using TimeSpans's TotalSeconds
You should parse your string to a TimeSpan:
CultureInfo provider = CultureInfo.InvariantCulture;
TimeSpan ts = TimeSpan.ParseExact(TimeToSplit, "mm\\:ss\\,ff", provider);
return ts.TotalSeconds
The problem is that you use a comma as the decimal separator of your number. Your code works fine on systems that have a locale that uses a comma for this (for example German); all others will break though, as a comma is a thousands separator there.
You can specify the locale when running double.Parse. A possible solution would be to replace the comma by a dot and use an invariant locale:
double.Parse(Timesplitter[1].Replace(',', '.'), CultureInfo.InvariantCulture)
This will allow you to use both dots or commas.
That being said, using TimeSpan as others suggested is definitely the better option.

How can I convert string to time object for calculation

how do I format output in seconds:milliseconds format?
TimeSpan start = TimeSpan.Parse(pair.Value[3]);
TimeSpan end = TimeSpan.Parse(pair.Value[4]);
Console.WriteLine(TimeSpan.Compare( start,end));
The code here is printing the difference in seconds. how can i fix it using string.format as i dont know the convention for milliseconds?
You need to look at the difference between the two timespans.
TimeSpan start = new TimeSpan(42); // 42 ticks
TimeSpan end = new TimeSpan(420000000);
TimeSpan diff = end.Subtract(start);
string ms = diff.Milliseconds.ToString();
string sec = ((int)diff.TotalSeconds).ToString();
Console.WriteLine(sec + ":" + ms);
How about
Console.WriteLine(end.Subtract(start).TotalMilliseconds)
If it's in seconds, you could just multiply the answer by 1000 and write that out as a string?
Otherwise, take a look at this MSDN article http://msdn.microsoft.com/en-us/library/bb882581.aspx

how to achieve timespan to string conversion?

I tried searching here, but it couldn't help me much ..
I want to convert time_span to string, I don't want to return the timespan in days .. but only HH:mm:ss. How to achieve that?
My sample code is here:
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString("HH:mm:ss");
Try using
DateTime d = new DateTime(time_span.Ticks);
string time = d.ToString("HH:mm:ss");
This should work:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString(), time_span.Minutes.ToString(),
time_span.Seconds.ToString());
As per comment if you want the double digits you could do:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString("00"), time_span.Minutes.ToString("00"),
time_span.Seconds.ToString("00"));
Edited:as per jimmy's comment,
string temp = string.Format("{0:00}:{1:00}:{2:00}",time_span.Hours, time_span.Minutes, time_span.Seconds);
Try this:
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString();
temp = string.Format("{0}:{1}:{2}", time_span.TotalHours, time_span.TotalMinutes, time_span.TotalSeconds);
Edit
After I read your comment on your question, that is you need to display zero hours for new days, my answer will give you total hours, minutes and seconds, not what you want.
(+1) Kelseys ;)
The code I have implemented is:
string temp = DateTime.Today.Add(time_span).ToString("HH:mm:ss");
Originally posted by Marc Gravell,
There is a much simpler way of doing this now (albeit only using framework 4), you just need to use the string literally, and you can do it directly on the TimeSpan instance.
time_span.ToString(#"hh\:mm\:ss")
That will output
00:26:39
Helpful now for people stumbling across this (like myself).
Cheers :)
Simply convert the value of ticks into a DateTime and then use its ToString()
var date1 = DateTime.Now;
var date2 = DateTime.Now.AddSeconds( -1000 );
var diff = date1 - date2;
var temp = new DateTime( diff.Ticks ).ToString( "HH:mm:ss" )
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
TimeSpan finalTime = (time_span_var + time_span);
Console.WriteLine(finalTime);
Console.WriteLine(finalTime - TimeSpan.FromHours(finalTime.Days * 24));
If the number of days is irrelevant then you have the solution, however I came across this answer searching for a conversion that gave hours in total, so 36 hours would need to be displayed as 36:00:00. Using some of the hints above this is what I came up with:
SomeLabel.Text = Math.Floor(ts.TotalHours).ToString() + ":" + ts.Minutes.ToString("D2") + ":" + ts.Seconds.ToString("D2");
Total Hours is always rounded down, minutes and seconds are padded to be 2 digits (00 - 09)

Categories

Resources