本文整理汇总了C#中System.TimeSpan.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# TimeSpan.ToString方法的具体用法?C# TimeSpan.ToString怎么用?C# TimeSpan.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.TimeSpan
的用法示例。
在下文中一共展示了TimeSpan.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FormatTimeSpanForDisplay
/// <summary>
/// Converts timespan to something like: "9d", "3d 22h", "18h", "3h 22m", "22m"
/// </summary>
/// <param name="timespan"></param>
/// <returns></returns>
/// <remarks>
/// Shows just minutes for t less than 1h, only hours between 6-24h, only days if 6d or more
/// </remarks>
public static string FormatTimeSpanForDisplay(TimeSpan timespan)
{
double totalHours = timespan.TotalHours;
if (totalHours < 0)
{
return "error";
}
else if (totalHours < 1)
{
return timespan.ToString("m'm'");
}
else if (totalHours < 6)
{
return timespan.ToString("h'h 'm'm'");
}
else if (totalHours < 24)
{
return timespan.ToString("h'h'");
}
else if (totalHours < 144)
{
return timespan.ToString("d'd 'h'h'");
}
else
{
return timespan.ToString("d'd'");
}
}
示例2: FormatTimeSpan
/// <summary>
/// Formats a timespan for logger output.
/// </summary>
/// <owner>JomoF</owner>
/// <param name="t"></param>
/// <returns>String representation of time-span.</returns>
internal static string FormatTimeSpan(TimeSpan t)
{
string rawTime = t.ToString(); // Timespan is a value type and can't be null.
int rawTimeLength = rawTime.Length;
int prettyLength = System.Math.Min(11, rawTimeLength);
return t.ToString().Substring(0, prettyLength);
}
示例3: FormatTimeSpan
public string FormatTimeSpan(TimeSpan timeSpan)
{
if (timeSpan.Hours != 0 || timeSpan.Days != 0)
return timeSpan.ToString("g", CultureInfo);
else
return timeSpan.ToString(@"mm\:ss");
}
示例4: PrettyDeltaTime
public static string PrettyDeltaTime(TimeSpan span, string rough = "")
{
int day = Convert.ToInt32(span.ToString("%d"));
int hour = Convert.ToInt32(span.ToString("%h"));
int minute = Convert.ToInt32(span.ToString("%m"));
if (span.CompareTo(TimeSpan.Zero) == -1) {
Log($"Time to sync the clock?{span}", ConsoleColor.Red);
return "a few seconds";
}
if (day > 1) {
if (hour == 0) return $"{day} days";
return $"{day} days {hour}h";
}
if (day == 1) {
if (hour == 0) return "1 day";
return $"1 day {hour}h";
}
if (hour == 0) return $"{rough}{minute}m";
if (minute == 0) return $"{rough}{hour}h";
return $"{rough}{hour}h {minute}m";
}
示例5: FormatTimeZoneOffset
private string FormatTimeZoneOffset(TimeSpan offset)
{
if (offset.TotalSeconds > 0)
return offset.ToString("'+'hhmm");
else
return offset.ToString("'-'hhmm");
}
示例6: FormatTimeSpanForDisplay
/// <summary>
/// Converts timespan to something like: "9d", "3d 22h", "18h", "3h 22m", "22m"
/// </summary>
/// <param name="timespan"></param>
/// <returns></returns>
/// <remarks>
/// Shows just minutes for t less than 1h, only hours between 6-24h, only days if 6d or more
/// </remarks>
public static string FormatTimeSpanForDisplay(TimeSpan timespan)
{
double totalMinutes = timespan.TotalMinutes;
if (totalMinutes < 0)
{
return "error";
}
else if (totalMinutes < 10)
{
return timespan.ToString("m'm 's's'");
}
else if (totalMinutes < 1 * 60)
{
return timespan.ToString("m'm'");
}
else if (totalMinutes < 6 * 60)
{
return timespan.ToString("h'h 'm'm'");
}
else if (totalMinutes < 24 * 60)
{
return timespan.ToString("h'h'");
}
else if (totalMinutes < 144 * 60)
{
return timespan.ToString("d'd 'h'h'");
}
else
{
return timespan.ToString("d'd'");
}
}
示例7: GetDurationFromSeconds
private static string GetDurationFromSeconds(double duration)
{
var span = new TimeSpan(0, 0, (int) duration);
var minutes = span.ToString("mm");
var hrs = span.ToString("hh");
return string.Format("{0} hrs {1} mins", hrs, minutes);
}
示例8: CatchingRoundBug
public void CatchingRoundBug()
{
// Summed ticks
const long value = 71731720000; //Total
// Specific flights
const long flight1 = 5228130000;
const long flight2 = 4842030000;
const long flight3 = 58475460000;
const long flight4 = 3186100000;
// Values
Debug.Print(value.TotalHoursWithMinutesAsDecimal());
Debug.Print(flight1.TotalHoursWithMinutesAsDecimal());
Debug.Print(flight2.TotalHoursWithMinutesAsDecimal());
Debug.Print(flight3.TotalHoursWithMinutesAsDecimal());
Debug.Print(flight4.TotalHoursWithMinutesAsDecimal());
Debug.Print((flight1 + flight2 + flight3 + flight4).ToString());
Debug.Print(value.ToString());
// Analyse the output of a clean timespan
var timeSpan = new TimeSpan(value);
Debug.Print(timeSpan.ToString());
Debug.Print(timeSpan.ToString("g"));
Debug.Print(timeSpan.TotalHours.ToString(CultureInfo.InvariantCulture));
Debug.Print(timeSpan.TotalHours.ToString("#00.0", CultureInfo.InvariantCulture) + " Please notice the rounding error that leads to an hour being added to the total");
Debug.Print(timeSpan.TotalHours.ToString("#00.00", CultureInfo.InvariantCulture) + " Please notice the fixed rounded value");
Debug.Print(timeSpan.TotalHours.ToString("#0.00", CultureInfo.InvariantCulture) + " Please notice the removed leading zero");
Debug.Print(timeSpan.TotalMinutes.ToString(CultureInfo.InvariantCulture));
Debug.Print(timeSpan.TotalMinutes.ToString("#00", CultureInfo.InvariantCulture));
// Original formula
var resultFormula = string.Format("{0}:{1}"
, timeSpan.TotalHours.ToString("#00.0").Substring(0, timeSpan.TotalHours.ToString("#00.0", CultureInfo.InvariantCulture).IndexOf(".", StringComparison.InvariantCulture))
, timeSpan.Minutes.ToString("#00"));
Debug.Print(resultFormula);
var resultFixedFormula = string.Format("{0}:{1}"
, timeSpan.TotalHours.ToString("#0.000", CultureInfo.InvariantCulture).Substring(0, timeSpan.TotalHours.ToString("#0.000", CultureInfo.InvariantCulture).IndexOf(".", StringComparison.InvariantCulture))
, timeSpan.Minutes.ToString("#00"));
Debug.Print(resultFixedFormula);
// Validate the resulting corrected formual is functioning
var result = value.TotalHoursWithMinutesAsDecimal();
Assert.AreEqual(result, "1:59");
}
示例9: Request
public Message Request(Message message, TimeSpan timeout)
{
ThrowIfDisposedOrNotOpen();
lock (this.writeLock)
{
try
{
File.Delete(PathToFile(Via, "reply"));
using (FileSystemWatcher watcher = new FileSystemWatcher(Via.AbsolutePath, "reply"))
{
ManualResetEvent replyCreated = new ManualResetEvent(false);
watcher.Changed += new FileSystemEventHandler(
delegate(object sender, FileSystemEventArgs e) { replyCreated.Set(); }
);
watcher.EnableRaisingEvents = true;
WriteMessage(PathToFile(via, "request"), message);
if (!replyCreated.WaitOne(timeout, false))
{
throw new TimeoutException(timeout.ToString());
}
}
}
catch (IOException exception)
{
throw ConvertException(exception);
}
return ReadMessage(PathToFile(Via, "reply"));
}
}
示例10: OutputRunStats
public void OutputRunStats(TimeSpan totalRuntime, IEnumerable<RunStats> runners, List<string> skippedTests)
{
var sb = new StringBuilder();
sb.AppendLine(_ganttChartBuilder.GenerateGanttChart(runners));
sb.AppendLine("<pre>");
sb.AppendLine("Total Runtime: " + totalRuntime.ToString());
foreach (var r in runners.OrderByDescending(t => t.RunTime))
{
AppendTestFinishedLine(sb, r);
}
if (skippedTests.Count > 0)
{
sb.AppendLine();
sb.AppendLine("Did not run:");
foreach (var r in skippedTests)
{
sb.AppendFormat("'{0}'", r);
sb.AppendLine();
}
}
sb.AppendLine("</pre>");
File.WriteAllText(_settings.ResultsStatsFilepath, sb.ToString());
}
示例11: TimeSpanDetailToMiliseconds
public static string TimeSpanDetailToMiliseconds(TimeSpan ts)
{
var sb = new StringBuilder();
try
{
var fmt = ts.Days > 0 ? @"dd\.hh\:mm\:ss\.fff" : @"hh\:mm\:ss\.fff";
var test = ts.ToString(fmt);
if (ts.Days > 0)
{
sb.Append($"{ts.Days:00} Days ");
}
sb.Append($"{ts.Hours:00} Hours ");
sb.Append($"{ts.Minutes:00} Minutes ");
sb.Append($"{ts.Seconds:00} Seconds ");
sb.Append($"{ts.Milliseconds:000} Milliseconds");
return sb.ToString();
}
catch
{
return string.Empty;
}
}
示例12: ScreenRecordForm
public ScreenRecordForm( IPluginHost pluginHost )
: base(pluginHost)
{
this.StickyWindow = new DroidExplorer.UI.StickyWindow ( this );
CommonResolutions = GetCommonResolutions ( );
InitializeComponent ( );
var defaultFile = "screenrecord_{0}_{1}.mp4".With ( this.PluginHost.Device, DateTime.Now.ToString ( "yyyy-MM-dd-hh" ) );
this.location.Text = "/sdcard/{0}".With ( defaultFile );
var resolution = new VideoSize ( PluginHost.CommandRunner.GetScreenResolution ( ) );
var sizes = CommonResolutions.Concat ( new List<VideoSize> { resolution } ).OrderBy ( x => x.Size.Width ).Select ( x => x ).ToList ( );
resolutionList.DataSource = sizes;
resolutionList.DisplayMember = "Display";
resolutionList.ValueMember = "Size";
resolutionList.SelectedItem = resolution;
rotateList.DataSource = GetRotateArgumentsList ( );
rotateList.DisplayMember = "Display";
rotateList.ValueMember = "Arguments";
var bitrates = new List<BitRate> ( );
for ( int i = 1; i < 25; i++ ) {
bitrates.Add ( new BitRate ( i ) );
}
bitrateList.DataSource = bitrates;
bitrateList.DisplayMember = "Display";
bitrateList.ValueMember = "Value";
bitrateList.SelectedItem = bitrates.Single ( x => x.Mbps == 4 );
var ts = new TimeSpan ( 0, 0, 0, timeLimit.Value, 0 );
displayTime.Text = ts.ToString ( );
}
示例13: btnListQueue_Click
private async void btnListQueue_Click(object sender, EventArgs e)
{
label1.Text = "Processing...";
txtResult.Text = "";
ActiveMQReader r = new ActiveMQReader(System.Configuration.ConfigurationManager.AppSettings["ActiveMQURL"], System.Configuration.ConfigurationManager.AppSettings["ActiveMQName"]);
StringBuilder s = new StringBuilder();
TimeSpan inicio = new TimeSpan(DateTime.Now.Ticks);
List<Tuple<string, string>> messages = r.ListQueue();
if (messages.Count() > 0)
{
TimeSpan fim = new TimeSpan(DateTime.Now.Ticks);
s.Append("=================================\r\n");
s.Append("LISTING...\r\n");
s.Append("=================================\r\n");
s.Append("Inicio: " + inicio.ToString() + "\r\n");
s.Append("=================================\r\n");
s.Append("Fim: " + fim.ToString() + "\r\n");
s.Append("=================================\r\n");
s.Append("Tempo Total: " + (fim - inicio).ToString() + "\r\n");
s.Append("=================================\r\n");
s.Append("Total Msg: " + messages.Count() + "\r\n");
s.Append("=================================\r\n");
foreach (Tuple<string, string> t in messages)
{
s.Append(t.Item1 + " - at " + t.Item2 + "\r\n");
}
txtResult.Text = s.ToString();
}
label1.Text = "Completed";
}
示例14: EventTimer
/// <summary>
/// Creates a <see cref="EventTimer"/>
/// </summary>
/// <param name="period"></param>
/// <param name="dayOffset"></param>
EventTimer(TimeSpan period, TimeSpan dayOffset)
: base(MessageClass.Component)
{
m_period = period;
m_dayOffset = dayOffset;
Log.InitialStackMessages = Log.InitialStackMessages.Union("Timer", string.Format("EventTimer: {0} in {1}", m_period.ToString(), m_dayOffset.ToString()));
}
示例15: Request
public Message Request(Message requestMessage, TimeSpan timeout)
{
ThrowIfDisposedOrNotOpen();
lock (this.writeLock)
{
try
{
// Write the request message
this.WriteRequestMessage(requestMessage);
// Wait for the response
SoapMessageTableEntity soapMessage;
if (!this.WaitForReplyMessage(timeout, out soapMessage))
{
throw new TimeoutException(timeout.ToString());
}
// Read the reply message
Message replyMessage = this.ReadMessage(string.Format(ConfigurationConstants.ReplyTable, this.tableName), soapMessage);
return replyMessage;
}
catch (StorageException exception)
{
throw new CommunicationException(exception.Message, exception);
}
}
}