2012-01-03 2 views
1

분이 3 자리 숫자로 표시 될 때 두 개의 시간 소인 사이의 차이를 계산하는 데 문제가 있습니다. 180 : 22 = 180 분 22 초.C#의 시차, 3 자리 숫자 형식의 분

180 : 22, 122 : 11

또는

232 : 21, 31:34

그래서, 당신은 내가 좋아하는 타임 스탬프의 차이를 얻을 수있는 방법 나를 도울 수

업데이트 : 문자열로 정의 된 두 번의 차이를 가져와야합니다. 문제가되는 것은 문자열 (시간)이 60 분을 초과하고 한계를 넘었다는 것입니다. (: 22, 122 : 11, 232 : 21, 31:34 180)

+1

이 시간 값이 실제로 어떤 유형인지 보여주는 몇 가지 코드를 게시하십시오. 날짜 시간? 시간 범위? ... 결과 차이점은 어떤 유형이어야합니다. –

+1

Like DateTime.Now.Subtract (DateTime.Now) .TotalMinutes 또는 날짜 부분이없는 특수한 방법으로 표시된 분 및 초 부분 만 있습니까? – keni

답변

1

사용 System.TimeSpan 구조 : 그래서 위의 예처럼 차이를 확인하는 방법을 알아야

var seconds=(new TimeSpan(0, 180, 22)-new TimeSpan(0, 122, 11)).TotalSeconds; 
var minutes=(new TimeSpan(0, 232, 21)-new TimeSpan(0, 31, 34)).TotalMinutes; 
+2

Downvoter 관심을 갖는 분? 이것은 나에게 좋게 보인다. –

+0

잘못된 답변을 제공합니다. 특히 초. – McKay

+0

동의하지 않습니다. var 초 = 3491, var 분 = 200,783333333333. 결과는 정확합니다. – CedX

0

다음은 클래스의 그 이 물건 할 것 : 여기

public class CrazyTime 
{ 
    public TimeSpan TimeSpanRepresentation { get; set; } 
    public CrazyTime(TimeSpan timeSpan) 
    { 
     this.TimeSpanRepresentation = timeSpan; 
    } 
    public CrazyTime(string crazyTime) 
    { 
     // No error checking. Add if so desired 
     var pieces = crazyTime.Split(new[] { ':' }); 
     var minutes = int.Parse(pieces[0]); 
     var seconds = int.Parse(pieces[1]); 
     TimeSpanRepresentation = new TimeSpan(0, minutes, seconds); 
    } 
    public static CrazyTime operator-(CrazyTime left, CrazyTime right) 
    { 
     var newValue = left.TimeSpanRepresentation - right.TimeSpanRepresentation; 
     return new CrazyTime(newValue); 
    } 
    public override string ToString() 
    { 
     // How should negative Values look? 
     return ((int)Math.Floor(TimeSpanRepresentation.TotalMinutes)).ToString() + ":" + TimeSpanRepresentation.Seconds.ToString(); 
    } 
} 

것은 사용될 수있는 방법은 다음과 같습니다이 작동

 var a = new CrazyTime("123:22"); 
     var b = new CrazyTime("222:11"); 
     var c = b - a; 
     Console.WriteLine(c); 
+0

나는 string.Split()의 사용을 좋아한다. –

0

:

string time1 = "180:22"; 
string time2 = "122:11"; 

TimeSpan span1 = getTimespan(time1); 
TimeSpan span2 = getTimespan(time2); 

TimeSpan diff = span1 - span2; 

getTimespan은 올바르게 문자열을 구문 분석해야합니다. Regex를 사용하기로 결정했는데, 특히 구분 기호 ":"가 변경되지 않으면 어떤 경로로든 갈 수 있습니다.

private static TimeSpan getTimespan(string time1) 
{ 
    Regex reg = new Regex(@"\d+"); 
    MatchCollection matches = reg.Matches(time1); 
    if (matches.Count == 2) 
    { 
     int minutes = int.Parse(matches[0].Value); 
     int seconds = int.Parse(matches[1].Value); 
     return new TimeSpan(0, minutes, seconds); 
    } 
    return TimeSpan.Zero; 
} 
관련 문제