How can I convert string to time object for calculation - c#

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

Related

TimeSpan formatting to minutes ans seconds without hours

I need format TimeSpan to minutes and seconds(without hours), I looks to MSDN formatting but not found any example which I can reuse.
Example of what I need:
TimeSpan.FromSeconds(1) --> 00:01
TimeSpan.FromSeconds(60) --> 01:00
TimeSpan.FromSeconds(3600) --> 60:00
TimeSpan.FromSeconds(36000) --> 600:00
Any ideas which format possible use to convert TimeSpan to string in minutes:seconds format?
Try this:
var timeSpan = TimeSpan.FromSeconds(3123);
var result = string.Format("{0:D2}:{1:D2}", (int) timeSpan.TotalMinutes, timeSpan.Seconds);
// result = "52:03"
You can use TimeSpan.TotalMinutes for the first part and also pad the number of seconds with a custom format string:
var formatted = string.Format("{0}:{1:D2}", (int)ts.TotalMinutes, ts.Seconds);
For those who prefer to just pass string format
timespan.ToString("mm\\:ss");

Convert Decimal to Hours Minutes and Seconds in C# .Net

I have an minutes field in a database like 138.34 that I need to convert back to HH:MM:SS What is the easiest way to do this?
You can use the TimeSpan.FromMinutes(minutesInDouble), pass the above value in double format.
For more information - check MSDN link here
Use the TimeSpan structure:
var timeSpan = TimeSpan.FromMinutes(138.34);
int hh = timeSpan.Hours;
int mm = timeSpan.Minutes;
int ss = timeSpan.Seconds;
Result:
Console.WriteLine("Hours:{0} Minutes:{1} Seconds:{2}", hh, mm, ss);
// Hours:2 Minutes:18 Seconds:20

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

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")

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)

How to Round to the Nearest 0.5?

in my application
Ex 1: Start time 12.30
(-)End time 16.00 here i get the value as 3.7 but i need to show this 3.7 as 3.5 in my application
Ex 2: Start time 12.00
(-)End time 16.00 here i get the value as 4.0 here there is no need to alter the value
(1.7,2.7,3.7,4.7,.... etc ) as to be represented as(1.5,2.5,3.5,4.5,.. etc )
so how to write an function for this where if the vale contains(1.7,2.7) i should change to 1.5,2.5
or if it contains 1.0,2.0 then there is no need to replace any value?
This extension method ought to do the job:
public decimal RoundToNearestHalf(this decimal value)
{
return Math.Round(value * 2) / 2;
}
var num1 = (3.7).RoundToNearestHalf(); // 3.5
var num1 = (4.0).RoundToNearestHalf(); // 4.0
I've used the decimal type in the code because it seems you want to maintain base 10 precision. If you don't, then float/double would do just as well, of course.
Use the DateTime type. Subtracting DateTime types returns a TimeSpan. Use TimeSpan.TotalHours to get your result. E.g.:-
var x = DateTime.Parse("12:30");
var y = DateTime.Parse("16:00");
Console.WriteLine((y - x).TotalHours);
Use DateTime type to work with time. Example:
string time1 = "12:30";
string time2 = "16:00";
TimeSpan diff = DateTime.Parse(time2)-DateTime.Parse(time2);
string diffString = diff.ToString("hh:mm"); // will be 03:30
Multiply hours with 60 and add minutes. You'll get total number of minutes.
12hours and 30 minutes = 720 + 30 = 750 minutes.
16 hours = 960 minutes.
Subtract the first value from the other and divide it by 60
(960 - 750) / 60 = 210 / 60 = 3.5
You should use TimeSpan and round it off:
TimeSpan startTime = new TimeSpan(12, 30, 0);
TimeSpan endTime = new TimeSpan(16, 0, 0);
TimeSpan span = endTime - startTime;
double totalHours = span.TotalHours;
double roundedToHalf = Math.Round(totalHours * 2) / 2;
Console.WriteLine(roundedToHalf);
UPDATE:
If the start and end time are from different dates, you should use DateTime for startTime and endTime.
If the values in your question represent times you can't do decimal arithmetic with them and expect time values as results.
You need to manipulate the values as times
I don't know C#, but it must have some time functions.
Have the times as DateTime then use Timspan to find the difference between the two times?
Times are not integers or floats. You can't work with them as if they are - you wouldn't try to do integer math using the String class, would you?
DateTime and TimeSpan are you friends for this kind of data manipulation.
You can use the C# Floor and Ceil method of the Math Class. Read more about it in the below URLs:
http://msdn.microsoft.com/en-us/library/system.math.ceiling(VS.71).aspx
http://dotnetperls.com/math-floor
string i = "2.0";
if (i == "2.3" || i == "3.3" || i == "4.3")
{
string strReplace = i.Replace(".3", ".5");
}
else
{
string strReplace = i;
}

Categories

Resources