2011-03-02 4 views
3

문법적으로 현재 작동 시간을 표시하는 문자열을 반환하고 싶습니다. 예를 들어, 3 년 7 개월 11 일 1 시간 16 초 0 초로, 단수 단위가 복수가 아니어야하며, 0 단위는 복수이어야합니다. 아직 발생하지 않았 으면 0으로 표시해서는 안됩니다. (예 : 아직 발생하지 않은 경우 년, 월 등을 표시하지 않음)C에서 문법적으로 올바른 가동 시간

틱 메서드는 한 달 이상 작동하지 않으므로 ManagementObject를 사용하고 있지만 어떻게해야합니까? datetime 계산을하고 세분화합니다. (저는 C#이 매우 새로워서 다양한 함수를 수행하는 유틸리티를 만들어 다양한 것을 배울 수 있습니다.)

이것은 내가 지금 가지고있는 것이며, 많이 지옥 ...

어떤 도움을 주시면 대단히 감사하겠습니다.

 public string getUptime() 
    { 
     // this should be grammatically correct, meaning, 0 and greater than 1 should be plural, one should be singular 
     // if it can count in realtime, all the better 
     // in rare case, clipping can occur if the uptime is really, really huge 

     // you need a function that stores the boot time in a global variable so it's executed once so repainting this won't slow things down with quer 
     SelectQuery query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'"); 
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); 
     foreach (ManagementObject mo in searcher.Get()) 
     { 
      // this is the start time, do math to figure it out now, hoss 
      DateTime boot = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString()); 
      // or is it better to break up everything into days/hours/etc, i think its better to do that at the end before it gets returned 
     } 

     string now = DateTime.Now.ToShortDateString(); 







     return "3 years, 7 months, 11 days, 1 hour, 16 minutes and zero seconds"; // long string for testing label width 
    } 
+1

다른 언어로도이 작업을 수행 할 계획이 없습니까? –

답변

4

청춘 '문자열로 변환 - 당신이 이미 가지고 현재 시간 (DateTime.Now)와 비교 마지막 재부팅 시간의 DateTime를 사용합니다. 두 빼기 당신은 TimeSpan를 얻을 :

TimeSpan upDuration = DateTime.Now - boot; 

TimeSpan 당신은 지금 당신의 문자열을 구축하는 데 사용할 수있는 속성 일, 시간, 분을 가지고있다.

+0

이것은 내가 의미했던 것입니다. – msarchet

+0

오 부트가 범위를 벗어 났으므로 루프 앞에서 생성자를 추가 했으므로 부트가 루프 외부에서 액세스 할 수 있습니다. 도와 줘서 고마워! –

0

인터넷 검색 인터넷을 통해 나를 이러한 의사 클래스로 유도 한 무언가를 발견했습니다. 밥 스콜라에 ... 기본 코드에서

class Utils 
{ 

    public DateTime GetLastDateTime() 
    { 
     // Insert code here to return the last DateTime from your server. 
     // Maybe from a database or file? 

     // For now I'll just use the current DateTime: 
     return DateTime.Now; 
    } 

    public CustomTimeSpan GetCurrentTimeSpan() 
    { 
     // You don't actually need this method. Just to expalin better... 
     // Here you can get the diference (timespan) from one datetime to another: 

     return new CustomTimeSpan(GetLastDateTime(), DateTime.Now); 
    } 

    public string FormatTimeSpan(CustomTimeSpan span) 
    { 
     // Now you can format your string to what you need, like: 

     String.Format("{0} year{1}, {2} month{3}, {4} day{5}, {6} hour{7}, {8} minute{9} and {10} second{11}", 
      span.Years, span.Years > 1 ? "s" : "", 
      span.Months, span.Monts > 1 ? "s" : "", 
      span.Days, span.Days > 1 ? "s" : "", 
      span.Hours, span.Hours > 1 : "s" : "", 
      span.Minutes, span.Minutes > 1 : "s" : "", 
      span.Seconds, span.Seconds > 1 : "s" : ""); 
    } 

} 

class CustomTimeSpan : TimeSpan 
{ 

    public int Years { get; private set; } 
    public int Months { get; private set; } 
    public int Days { get; private set; } 
    public int Hours { get; private set; } 
    public int Minutes { get; private set; } 
    public int Seconds { get; private set; } 

    public CustomTimeSpan (DateTime originalDateTime, DateTime actualDateTime) 
    { 
     var span = actualDateTime - originalDateTime; 

     this.Seconds = span.Seconds; 
     this.Minutes = span.Minutes; 
     this.Hours = span.Hours; 

     // Now comes the tricky part: how to get the day, month and year part... 
     var months = 12 * (actualDateTime.Year - originalDateTime.Year) + (actualDateTime.Month - originalDateTime.Month); 
     int days = 0; 

     if (actualDateTime.Day < originalDateTime.Day) 
     { 
      months--; 
      days = GetDaysInMonth(originalDateTime.Year, originalDateTime.Month) - originalDateTime.Day + actualDateTime.Day; 
     } 
     else 
     { 
      days = actualDateTime.Day - originalDateTime.Day; 
     } 

     this.Years = months/12; 
     months -= years * 12; 
     this.Months = months; 
     this.Days = days; 
    } 


} 

크레딧을 작동 할 수 있습니다. How to calculate age using TimeSpan w/ .NET CF?