Displaying a formatted TimeSpan as string - c#

I'd like to display a TimeSpan value, formatted as mm:ss (minutes, seconds).
The code currently performs this like this:
var timeSpan = GetTimeUntilNextEvent();
var str = DateTime.MinValue.Add(timeSpan).ToString(#"mm\:ss");
I wonder whether that is correct code. I saw other samples that show this technique, but I am not really sure what is the reason for adding something to the MinValue of DateTime.
Why cannot this code be used ? It seems to product a valid result.
var str = DateTime.FromBinary(0).Add(timeSpan).ToString(#"mm\:ss");

You don't need DateTime to format a TimeSpan.
You could simply use the timespan ToString() method:
TimeSpan timeSpan = new TimeSpan(5, 12, 2);
String str = timeSpan.ToString(#"mm\:ss"));
Also see Link.

Related

How to parse a timespan in order to add it to a datetime?

I've got a string in the following format: 05/06/2019|1330|60
The output I'm looking for is: 05/06/2019T14:30:00
I'm attempting to parse out the TimeSpan portion right now:
public static string getProcedureEndingDateTime (string input) {
//05/06/2019|1330|60
string myDate = input.Split ( '|' ) [0];
DateTime myDateTime = DateTime.Parse (myDate);
string myTime = input.Split('|')[1];
string hours = myTime.Substring(0,2);
string minutes = myTime.Substring(2,2);
TimeSpan myTimeSpan = TimeSpan.Parse($"{hours}:{minutes}");
myDateTime.Add(myTimeSpan);
return myDateTime.ToString();
}
But right now, getting the following output:
To get the above output I'm calling my function like so:
Console.WriteLine (getProcedureEndingDateTime("05/06/2019|1330|60"));
How do I parse the string "1330" into a TimeSpan?
No need to us a Timespan here, just call ParseExact instead with a proper format to do it in one line.
var myDateTime = DateTime.ParseExact("05/06/2019|1330|60", "dd/MM/yyyy|HHmm|60", CultureInfo.InvariantCulture);
Console.WriteLine(myDateTime.ToString());
//this gives 2019-06-05 1:30:00 PM, format depends on your PC's locale
I don't know what the 60 part is, you can adjust the format or substring it out beforehand.
The problem is because Add() returns a new DateTime instance, which means you're currently discarding it. Store it, and return that from your function instead, like so:
var adjusted = myDateTime.Add(myTimeSpan);
return adjusted.ToString();
Try using the numeric values as exactly that, numbers.
Also, the other issue with your code is the DateTime.Add() method doesn't add to that DateTime variable. Instead it returns a new variable, which you are ignoring.
Try this:
public static string getProcedureEndingDateTime (string input) {
string[] parts = input.Split('|');
string myDate = parts[0];
DateTime myDateTime = DateTime.Parse (myDate);
string myTime = parts[1];
if (!int.TryParse(myTime.Substring(0,2), out int hours))
hours = 0;
if (!int.TryParse(myTime.Substring(2,2), out int minutes))
minutes = 0;
TimeSpan myTimeSpan = new TimeSpan(hours, minutes, 0);
myDateTime += myTimeSpan;
return myDateTime.ToString();
}
Assuming the date shown is May 6th (and not June 5th), and also assuming the 60 represents a time zone offset expressed in minutes west of GMT, and also assuming you want the corresponding UTC value, then:
public static string getProcedureEndingDateTime (string input) {
// example input: "05/06/2019|1330|60"
// separate the offset from the rest of the string
string dateTimeString = input.Substring(0, 15);
string offsetString = input.Substring(16);
// parse the DateTime as given, and parse the offset separately, inverting the sign
DateTime dt = DateTime.ParseExact(dateTimeString, "MM/dd/yyyy|HHmm", CultureInfo.InvariantCulture);
TimeSpan offset = TimeSpan.FromMinutes(-int.Parse(offsetString));
// create a DateTimeOffset from these two components
DateTimeOffset dto = new DateTimeOffset(dt, offset);
// Convert to UTC and return a string in the desired format
DateTime utcDateTime = dto.UtcDateTime;
return utcDateTime.ToString("MM/dd/yyyy'T'HH:mm:ss", CultureInfo.InvariantCulture);
}
A few additional points:
Not only is the input format strange, but so is your desired output format. It is strange to see a T separating the date and time and also see the date in the 05/06/2019 format. T almost always means to use ISO 8601, which requires year-month-day ordering and hyphen separators. I'd suggest either dropping the T if you want a locale-specific format, or keep the T and use the standard format. Don't do both.
In ISO 8601, it's also a good idea to append a Z to UTC-based values. For DateTime values, the K specifier should be used for that. In other words, you probably want the last line above to be:
return utcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);
// outputs: "2019-05-06T14:30:00Z"
You might want to not format a string here, but instead return the DateTime or DateTimeOffset value. It's usually better to create a string only at the time of display.
Don't forget that the DateTime struct is immutable. In your question you were ignoring the return value of the Add method.

Add time duration to date using addHours() in c#

I want to add time duration to my datetime variable. I am reading the duration from a csv file. The format of duration is 0:29:40 or 1:29:40. When i add this to datetime variable it gives exception of incorrect format. How can I add the duration using this format. Previously I had duration as a simple integer like "6" or "7" but now the format is this "0:29:40" I don't know how to change my code to accommodate this format.
Previously i was doing this
double hours = Convert.ToDouble(row.Cells[2].Value.ToString());
DateTime newdate = finaldate.AddHours(hours);
row.Cells[2].Value.ToString() reads the value from csv
Any help is appreciated, Thanks
You don't need to parse to a double. Parse to a TimeSpan. Something like:
var source = "0:29:40";
var ts = TimeSpan.Parse(source);
Now ts is your time span. And the nice thing with TimeSpan is you can just add it to a DateTime:
DateTime newdate = finaldate + ts;
You are going to need to use the TimeSpan.Parse() or TimeSpan.ParseExact() method to properly parse your string and then simply add that TimeSpan result to your existing date:
var time = TimeSpan.Parse(row.Cells[2].Value.ToString());
DateTime newDate = finalDate.Add(time);
If you need to explicitly specify what each of the values of your time represent, then the TimeSpan.ParseExact() method will allow you to provide a formatting string to specify this:
// This will assume that 1:29:40 is hours, minutes, and seconds
var time = TimeSpan.ParseExact(row.Cells[2].Value.ToString(), #"h\:m\:s", null);

How can I remove Milliseconds from the TimeSpan in C#? [duplicate]

This question already has answers here:
How can I String.Format a TimeSpan object with a custom format in .NET?
(20 answers)
Closed 6 years ago.
I am new to c# and using windows forms. the result of this code is: 01:38:07.0093844 . Anyone knows how can I remove the millisecond part (0093844) from the result (ts) I want the result to look like this : 01:38:07 (H:mm:ss) without millisecond .
Please help .Thank you
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)); //Difference
//result of ts = 01:38:07.0093844
Create an extension method:
public static class TimeExtensions
{
public static TimeSpan StripMilliseconds(this TimeSpan time)
{
return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds);
}
}
Usage:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)).StripMilliseconds();
To format (make into a string) without milliseconds use this:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime));
string formatted = ts.ToString(#"dd\.hh\:mm\:ss");
You can round through a division and a multiplication by the number of Ticks per second:
ts = new TimeSpan(ts.Ticks / TimeSpan.TicksPerSecond * TimeSpan.TicksPerSecond);
Internally a TimeSpan is "simply" a number of Ticks. By doing an integer division and an integer multiplication you can "round" them.
What the object contains and what you want on the screen are separate concerns, do not mix the 2. If you want it formatted on the screen as hourse, minutes, seconds then use ToString() and include that in your format. Example:
var forScreen = ts.ToString("hh:mm:ss");
See all the formatting options available on MSDN Custom TimeSpan Format Strings.
Edit
As mentioned, you can make it whatever you want. Here is an example of ToString which builds out a human readable string. These formatters are meant to build a string that you can display so you do not have to actually make changes to the underlying data. This is your presentation logic.
dif.ToString("'Elapsed: 'dd' days, 'hh' hours, 'mm' minutes and 'ss' seconds'")
You can just format the time like below:
string NewDateTime = ts.ToString("yyyy-MM-dd hh:mm:ss");

How to Convert string "07:35" (HH:MM) to TimeSpan

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.
Right now I have a "old fashion style":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Use TimeSpan.Parse to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

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

Categories

Resources