3

DateTime을 다시 읽는 중입니까? 가치관. 이제 NextUpdate DateTime이 표시되는지 확인합니다. HasValue이고 그럴 경우 해당 시간을 UTC으로 변환하십시오.nullable DateTime을 UTC로 변환하는 방법 DateTime

이 글을 읽고 나서 null coalescing operator을 사용해야하지만 내 할당에 따르면 해당 연산자를 사용할 때 System.NUllable에 ToUniversalTime()에 대한 정의가 없다고 나와 있습니다.

나는 비슷한 질문을했지만, 그것에 대해서는 행운을 찾지 못했습니다.

질문 : UTC에 널 날짜 시간 값을 변환 할 수있는 방법

?

코드 :

나는 DateTime? 값을 가지고, 그래서 UTC 해당 DateTie을 변환 할 경우 -

  if (escalation.NextUpdate.HasValue) 
      { 
       escalation.NextUpdate = escalation.NextUpdate ?? escalation.NextUpdate.ToUniversalTime(); 
      } 
      else 
      { 
       escalation.NextUpdate = null; 
      } 

모델의 내 NextUpdate 특성 :

public DateTime? NextUpdate { get; set; } 
+0

''escalation.NextUpdate? .ToUniversalTime()'을 의미할까요? –

+3

는''escalation.NextUpdate.ToUniversalTime()''을''escalation.NextUpdate.Value로 변경합니다.ToUniversalTime()'' –

+0

@ EhsanSajjad 위의 작업 :) –

답변

6

코드가 여러 가지면에서 잘못되었습니다. 그것이 달리 우측 널이 아닌 경우

?? 작업자는 좌측 를 반환한다.
이미 escalation.NextUpdate.HasValuetrue임을 확인 했으므로 왼쪽이 null이 아니며 동일한 날짜를 다시 지정합니다 (UTC로 변환하지 않음).

Nullable<DateTime>은 (는) ToUniversalTime()을 선언하지 않으므로이 값을 사용해야합니다.

그래서 최종 코드는 다음과 같아야합니다

if (escalation.NextUpdate.HasValue) 
    escalation.NextUpdate = escalation.NextUpdate.Value.ToUniversalTime(); 

이나와 C# 6

escalation.NextUpdate = escalation.NextUpdate?.ToUniversalTime(); 

else 지점에 대한 필요가 어쨌든 null 될 경우와 같이이 없습니다.

+0

은 "에스컬레이션을하지 않아도됩니다. NextUpdate? .Value.ToUniversalTime()''? –

+0

@ EhsanSajjad 나는 처음으로 그렇게 생각했다. 그러나 놀랍게도 이것은 잘 작동합니다. –

+0

@EhsanSajjad 좋은 질문 이지만요? 연산자는 자동으로 값 속성 – MikeT

3

당신은 다음의 간단한 C# 6을 사용하는 경우

escalation.NextUpdate?.ToUniversalTime(); 

다음과 같이 번역됩니다. NextUpdate가 null이 아닙니다. ToUniversalTime() else return null

if yo 아마 드러내는 것은 당신이 널 (NULL)의 Value 속성을 놓쳤다과의 사용을 수정 한 경우이 기본적으로 전체와 동일한 가장 좋은

escalation.NextUpdate.HasValue ? (DateTime?)escalation.NextUpdate.Value.ToUniversalTime():null; 

경우 u는 다음 인라인 # 6 c를 사용할 수 없습니다 ?? 연산자