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)
Related
I am converting minutes into hours. So if I have minutes = 12534. The result should be 208:54. The below code fails to bring this result.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(#"hh\:mm");
Console.WriteLine(workHours);
The result is 16:54.
How to get it correct?
var totalMinutes = 12534;
Console.WriteLine("{0:00}:{1:00}", totalMinutes / 60, totalMinutes % 60);
Or
var totalMinutes = 12534;
var time = TimeSpan.FromMinutes(totalMinutes);
Console.WriteLine("{0:00}:{1:00}", (int)time.TotalHours, time.Minutes);
See https://dotnetfiddle.net/gYEsj2 to play with this
The correct way to use is not using the ToString overload of DateTime – because there is no possibility to show the TotalHours there – but the string.Format method:
string.Format("{0:00}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
You need use TimeSpan.TotalHours Property
The TotalHours property represents whole and fractional hours, whereas the Hours property represents whole hours.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(#"hh\:mm");
Console.WriteLine(spWorkMin.TotalHours);
https://dotnetfiddle.net/JRCLra
The format specifier hh will show the hour part, which is not the total hours. You have to manually create a string using TotalHours cast into ints to show it as you want and add the minutes to that.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
From MSDN documentation:
The "hh" custom format specifier outputs the value of the TimeSpan::Hours property, which represents the number of whole hours in the time interval that is not counted as part of its day component.
One quick way of getting the result you want would be something like the following:
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
Personnaly I use this:
public static double MinutsTohHours(int Minuti)
{
double Tempo = 0;
Tempo = ((double)(Minuti % 60) / 100);
var n = (double)Minuti / 60;
return Math.Floor((double)Minuti / 60) + Tempo;
}
using System;
var days = 1;
var hours = 23; //max 23
var min = 12; //max 59
var TotalMin = (days*24*60)+(hours*60)+min;
Console.WriteLine("TotalMins "+ TotalMin);
//return back to the original days,hours,minutes
var Days = (TotalMin/(24*60));
var _minutes = (TotalMin%(60*60));
var Hours = (_minutes/60);
var Minutes = _minutes - (Hours*60);
Console.WriteLine($"{Days} , {Hours} , {Minutes}");
I need to convert
20141013T155544.673-04/0
To a DateTime type.
Presently I am manually parsing the string out
//20130605T154727.683-04/0
//20130806T143808.018-04
//var a = new DateTime();
var year = segmentDate[0].ToString(CultureInfo.InvariantCulture) + segmentDate[1].ToString(CultureInfo.InvariantCulture) + segmentDate[2].ToString(CultureInfo.InvariantCulture) + segmentDate[3].ToString(CultureInfo.InvariantCulture);
var month = segmentDate[4].ToString(CultureInfo.InvariantCulture) + segmentDate[5].ToString(CultureInfo.InvariantCulture);
var day = segmentDate[6].ToString(CultureInfo.InvariantCulture) + segmentDate[7].ToString(CultureInfo.InvariantCulture);
//s[8] == "T";
var hours = segmentDate[9].ToString(CultureInfo.InvariantCulture) + segmentDate[10].ToString(CultureInfo.InvariantCulture);
var minutes = segmentDate[11].ToString(CultureInfo.InvariantCulture) + segmentDate[12].ToString(CultureInfo.InvariantCulture);
var seconds = segmentDate[13].ToString(CultureInfo.InvariantCulture) + segmentDate[14].ToString(CultureInfo.InvariantCulture);
string milliseconds = null;
if (segmentDate.Contains("."))
milliseconds = segmentDate.Split('.')[1].Split('-')[0];
if (milliseconds != null && milliseconds.Contains((" ")))
{
milliseconds = milliseconds.Split(' ')[0];
}
var offset = Convert.ToInt32(segmentDate.Split('-')[1].Split('/')[0]);
var a = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month),
Convert.ToInt32(day), Convert.ToInt32(hours), Convert.ToInt32(minutes),
Convert.ToInt32(seconds), Convert.ToInt32((milliseconds ?? "0"))).AddHours(offset);
But that is a bad idea - and I cannot believe that this format isnt specified somewhere (that I have been able to find).
Any help is appreciated.
Thank you!
Update
4 digit year
2 digit month
2 digit day
T - denotes start of the time portion
2 digit hour
2 digit minute
2 digit second
. - denotes start of MS
3 digit ms
TZ offset (-04)
/0 I believe is offset minutes
Update2
So I have been playing with TryParseExact and ParseExact - and cannot come up with a format string that will pull this into a DateTime/DateTimeOffset type.
I also consulted with the supplier of this value and they also have a manual process to parse it out, like I posted already.
I cannot accept that this is the only way to achieve the desired result, and as such, will continue to play with it.
But if anyone else has suggestions, they are welcome here.
Here's the closest I've gotten:
string s = "20141013T155544.673-04/0";
var dt = DateTime.ParseExact(s,"yyyyMMddTHHmmss.fffzz/0",CultureInfo.InvariantCulture);
If the /0 represents minutes (and can be 0 or 30 then you could do a little manipulation to convert that to a "standard" time zone indicator:
string s = "20141013T155544.673-04/30";
string s2 = s.Replace("/0",":00").Replace("/30",":30");
var dt = DateTime.ParseExact(s2,"yyyyMMddTHHmmss.fffzzz",CultureInfo.InvariantCulture);
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 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 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